Entity Framework DeleteObject child

What's the best way to delete an object (and its children) using EF? I would like to pass only the id for the object to be deleted and remove the EF files from the dependent data (foreign key data). Do I need to first retrieve the object based on the ID and then call "DeleteObject"?

+2


source to share


1 answer


If you have a cascade configured in your database, then removing this principle should be sufficient.

You can do this without querying the database to GET the thing to be deleted using Stub objects like:

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

      

Of course it's not the whole story if there are links or fields used for concurrency checks that you need too.

If, on the other hand, you only have a cascading delete in the model (i.e., there is no cascade in the database), you need to get ALL 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 problem (what it expects) is redundantly deleting in order to keep the ObjectContext in line with what it expects in the database.

Hope it helps

Alex

PS I have tips in this section on my MSDN blog. Check out tip 33 (cascade delete) and tip 26 (stub objects)

+8


source







All Articles