In Entity Framework, you may delete an object and all of its connected entities.

ado.net entity-framework

Question

Is there a way to remove an object from EF along with all of its associated entities without having to manually go through the object graph and remove each one?

I have a 1:N connection between my SalesOrder and SalesOrderDetails, for instance. I want all SalesOrderDetails to be automatically erased when I delete a SalesOrder.

Can this be done in EF?

1
26
2/1/2013 11:22:02 AM

Accepted Answer

This is not something you ought to be doing with Entity Framework. Support for all widely used relational databasesON CASCADE DELETE on foreign keys, which is far more effective. I advise you to just accept that.

26
6/1/2009 11:59:21 PM

Popular Answer

Alex Jamese, who posted his response, has a thorough piece on the subject in this article.

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.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow