Does anyone know how to delete an object and all of its related entities inside of EF without manually traversing the object graph and deleting each one?
For example, I've got SalesOrder and SalesOrderDetails with a 1:N relationship between them. When I delete a SalesOrder, I want all SalesOrderDetails to be deleted automatically.
Is this possible in EF?
You should not be doing this in the Entity Framework. All popular relational databases support ON CASCADE DELETE
on foreign keys which is a lot more efficient as well. I suggest you just go with that.
in this article, Alex Jamese (who post his answer), has a complete article on the topic.
http://blogs.msdn.com/b/alexj/archive/2009/08/19/tip-33-how-cascade-delete-really-works-in-ef.aspx
The EF is responsible for the correctness of the ObjectContext after SaveChanges(). So the EF attempts to synchronize the ObjectContext, with the expected database state after the expected cascade in the database. A tell tale sign of this is that if you open up something like SqlProfiler, you will notice the EF issuing DELETE requests for dependent entities that it knows about (i.e. that are loaded in the ObjectContext) when a principal is deleted. Essentially what is happening here is that the Entity Framework expects that deleting the principal in the database, will delete all it’s dependents in the database. So it issues, what should be, a redundant DELETE to request itself so the dependents already loaded are deleted from the ObjectContext. The key thing to note is that the EF does not retrieve all the dependent entities and issue deletes for them: It only deletes dependents that are already in memory.