Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete an object and all of its related entities in Entity Framework

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?

like image 804
LPCRoy Avatar asked Jun 01 '09 22:06

LPCRoy


People also ask

How do I delete all records in Entity Framework?

Table select o; foreach (var row in rows) { dataDb. Table. Remove(row); } dataDb. SaveChanges();

What is Cascade delete in Entity Framework?

Cascading deletes are needed when a dependent/child entity can no longer be associated with its current principal/parent. This can happen because the principal/parent is deleted, or it can happen when the principal/parent still exists but the dependent/child is no longer associated with it.

How do I Soft delete in Entity Framework?

The Soft Delete feature allows you to flag entities as deleted (Soft Delete) instead of deleting them physically (Hard Delete). The soft delete feature can be achieved by using the 'IEFSoftDelete' interface. By default, this interface is always added to the manager.


2 Answers

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.

like image 159
aleemb Avatar answered Sep 28 '22 18:09

aleemb


in this article, Alex Jamese (who post his answer), has a complete article on the topic.

Link

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.

like image 32
Marco Staffoli Avatar answered Sep 28 '22 17:09

Marco Staffoli