Search code examples
c#.netentity-frameworkobjectcontext

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


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.

Solution

  • 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.