How to delete a EntityObject, that belongs to a Collection of EntityObjects, from the ObjectContext?

615 Views Asked by At

I would like to perform a delete on my ObjectContext.

This is my code:

var tempList = someEntityObject.SomeCollectionOfEntityObject;

foreach (var item in tempList)
{
    someObjectContext.DeleteObject(item);
    tempList.Remove(item);
}

I want to delete someEntityObject, but before i can, i need to delete all objects in SomeCollectionOfEntityObject. I have a foreign key constraint that prevents me from deleting someEntityObject.

When the foreach tries to loop the second time i get this error:

System.InvalidOperationException occurred
  Message=Collection was modified; enumeration operation may not execute.
3

There are 3 best solutions below

1
On BEST ANSWER

Instead of using foreach on tempList you can populate the collections to some real temporary list first.

var realList = tempList.ToList();

Then you clear tempList and then you can iterate over realList.

0
On

Use a while loop instead:

while(someEntityObject.SomeCollectionOfEntityObject.Count > 0)
{ 
    someObjectContext.DeleteObject(someEntityObject.SomeCollectionOfEntityObject.First());
}
0
On

Another option is to specify cascade delete on the relationship.

This will cause all of the records in SomeCollectionOfEntityObject to be deleted automatically when you delete someEntityObject.

Note that you must do this on both the model and the database for it to work reliably. See this post for more information: http://blogs.msdn.com/b/alexj/archive/2009/08/19/tip-33-how-cascade-delete-really-works-in-ef.aspx.