views:

40

answers:

1

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. This code proceedes on Clear() but fails on SaveChanges() because related items are connected to their document via FK and FK is mandatory. So I guess they somehow remain floating up in the air without a foreign key after Clear().

Do I solve this with a foreach loop over the collection calling Remove() on each item or is there another way?

// remove existing document items to prepare for refreshing them
existing.DocumentItems.Clear();
// adds new Document Items
PrepareInvoice(existing, collection);
_repository.SaveChanges();
+1  A: 

Clear just removes the reference, but doesn't delete the entiy.

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.

Nix
First I think its ironic we are talking about how `Clear` is unclear. My understanding is that they are different. Clear just says remove the pointer to (in memory) these objects. `Remove` says remove from my list and mark for deletion... please correct me if i have said anything invalid.
Nix