views:

466

answers:

1

What is the best way to delete an object (and its child objects) using EF? I'd like to pass just the id for the object to delete, and have EF handle deleting its dependent data (foreign key'd data). Do I have to retrieve the object first based on the id and then call "DeleteObject"?

+3  A: 

If you have cascade configured in the database, then deleting the principle should be enough.

You can do this without a query to the database to GET the thing to be deleted using Stub entities like this:

var stub = new Principal{ID = idToDelete};
ctx.AttachTo("PrincipalsEntitySetName", stub);
ctx.DeleteObject(stub);

Of course this is not the whole story if there are references or fields used for concurrency checks you will need those too.

If on the other hand you only have a cascade delete in the model (i.e. there is no cascade in the database) you will need to get ALL the dependents in memory first, and then call delete:

var stub = new Principal{ID = idToDelete};
ctx.AttachTo("PrincipalsEntitySetName", stub);
stub.Dependendents.Load();
ctx.DeleteObject(stub);

This only works because the EF issues (what it expects to be ) redundant deletes to keep the ObjectContext in sync with what it expects to happen in the database.

Hope this helps

Alex

PS I have some tips on this topic on my MSDN blog. Check out tip 33 (cascade delete) and tip 26 (stub entities)

Alex James