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?
Table select o; foreach (var row in rows) { dataDb. Table. Remove(row); } dataDb. SaveChanges();
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With