I have two tables Employee
and Address
. Employee
is my main table and Address
is the child table related to Employee
via the foreign key AddressId
.
When I delete the Employee
record, the record from Address
is not deleted. How can I rewrite my code to do this?
Employee: [Id](Primary Key) [FirstName] [LastName] [Email] [AddressId] (Foreign Key -> Address.Id) [Code] Address: [Id] (Primary Key) [Details] [State] [Country]
This is my current 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; } }
You are looking for the
ON DELETE CASCADE
function, which will indicate to MySQL that a record should be deleted when its "parent" record (in another table) is deleted.Things like this: