What is the right way to delete all of the collection items of an EF entity? In the code below, DocumentItems is the collection of related document items for a document. Thi
Clear just removes the reference but doesn't delete the entity.
In your situation
existing.DocumentItems.Clear();
All DocumentItems
in the EntitySet
will get cleared but you will have to Remove/Delete the actual DocumentItem
or the commit with fail, just the same as it would if you tried to delete it in the database.
You need to loop through detach any references, and then delete the entity you wish to remove (unless its nullable
and in your situation, it is not)
Alternatively, I have seen implementations that use clear, and an AssociationChangedHandler
to automatically delete the old object. Basically, if the change is a "delete/remove" it calls DeleteObject()
on the orphaned object.