Heim > Fragen und Antworten > Hauptteil
Ich habe zwei Tabellen Employee
和 Address
。 Employee
是我的主表,Address
是通过外键 AddressId
与 Employee
zugehörige Untertabellen.
Wenn ich lösche Employee
记录时,来自 Address
, wird der Datensatz nicht gelöscht. Wie kann ich meinen Code dazu umschreiben?
Employee: [Id](Primary Key) [FirstName] [LastName] [Email] [AddressId] (Foreign Key -> Address.Id) [Code] Address: [Id] (Primary Key) [Details] [State] [Country]
Das ist mein aktueller Code:
public bool DeleteEmployee(int id) { using (var context=new EmployeeDBEntities()) { var employee = context.Employee.FirstOrDefault(x => x.Id == id); if (employee != null) { context.Employee.Remove(employee); context.SaveChanges(); return true; } return false; } }
P粉5584781502024-04-05 10:33:38
您正在寻找 ON DELETE CASCADE
功能,该功能将向 MySQL 指示当删除其“父”记录(在另一个表中)时应删除该记录。
类似这样的事情:
CREATE TABLE address ( Id INT PRIMARY KEY AUTO_INCREMENT, Details VARCHAR(255) NOT NULL, State VARCHAR(255) NOT NULL, Country VARCHAR(255) NOT NULL ); CREATE TABLE employee ( Id INT PRIMARY KEY AUTO_INCREMENT, FirstName VARCHAR(255) NOT NULL, LastName VARCHAR(255) NOT NULL, Email VARCHAR(255) NOT NULL, AddressId INT NOT NULL, Code VARCHAR(255) NOT NULL, FOREIGN KEY (AddressId) REFERENCES address (Id) ON DELETE CASCADE );