Entity Framework Cascading deletes avoid the gotchas

22. April 2011

If you have ever had to do Cascading deletes with Entity Framework you have realized that it is happiness, but it has a couple of gotchas. The Context that entity framework uses will not fetch all items related from the database just to issue delete statements, it will however issue deletes from anything it knows about. So the solution is to have the delete from the database cascade or bring the items into the context manually.

Setting it in the EDMX is easy. Just pull up the properties on the association and set the on Delete behavior.

image

There are a few more step to help avoid the gotchas.

First if you can specify the Delete rule on the Foreign Keys in the database.

image

If you cannot do that you can specify an include for the collections that you want to delete.

var employee = entities.Employees.Include("EmployeeAddresses").FirstOrDefault();
entities.DeleteObject(employee);

Or slightly cleaner to read but more trips to the database is to load the collections.

var employee = entities.Employees.FirstOrDefault();
employee.EmployeeAddresses.Load();
entities.DeleteObject(employee);

 

Hope this helps

Entity Framework, Productivity , ,