views:

1939

answers:

2

Hi, Does anyone know how to delete an object and all of it's 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?

Thanks, Roy

+7  A: 

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.

aleemb
Yeap. If you have cascade delete on your relationships in database, and you bring that into an EF model, the EF will in fact delete dependent entities in memory to attempt to keep the in memory object graph in sync with the database. But you shouldn't rely on EF deleting related all related objects that is the job of the database.
Alex James
Thanks Alex, I was worried that CASCADE DELETE would mess up the in memory state but if EF is keeping it up to date then this works!
LPCRoy
+1  A: 

Hi, 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

Bugeo

related questions