我有两个表 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; } }
您正在寻找
ON DELETE CASCADE
功能,该功能将向 MySQL 指示当删除其“父”记录(在另一个表中)时应删除该记录。类似这样的事情: