我有兩個表 Employee
和 Address
。 Employee
是我的主表,Address
是透過外鍵 AddressId
與 Employee
關聯的子表。
當我刪除 Employee
記錄時,來自 Address
的記錄不會被刪除。我如何重寫我的程式碼來做到這一點?
Employee: [Id](Primary Key) [FirstName] [LastName] [Email] [AddressId] (Foreign Key -> Address.Id) [Code] Address: [Id] (Primary Key) [Details] [State] [Country]
這是我目前的程式碼:
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 );