29
votes

I'm currently using EF 4.0. My objective is to delete a child collection and add new ones to same parent.

 public void AddKids(int parentId, Kids newKids)
 {
    using (ModelContainer context = new ModelContainer(connectionString))
    {
        using (TransactionScope scope = new TransactionScope())
        {
            var query = from Parent _parent in context.Parents
                        where _parent.ParentId == parentId select _parent;

            Parent parent = query.Single();
            while (parent.Kids.Any())
            {
                context.Kids.DeleteObject(parent.Kids.First());
            }

            if (newKids != null)
            {
                foreach (Kid _kid in newKids)
                {
                    parent.Kids.Add(new Kid
                    {
                        Age = _kid.Age,
                        Height = _kid.Height
                    });
                }
            }
            scope.Complete();
        }
        context.SaveChanges(); //Error happens here
    }
}

The error is as from the title: Collection was modified; enumeration operation may not execute.

Any help would be appreciated.

2
@JustinNiessner: Thank you, I editted my question.madatanic
Now I'm also wondering where parent is defined.Justin Niessner
You open a new context yet you modify an old cached? instance of parent. I quess there is your problem. You should open the context, retrieve the parent and modify that.Polity
I have editted my question once more. Thank you guys.madatanic
I tried setting a complete mock copy of this up. It works fine for me :/.Joshua Enfield

2 Answers

52
votes

You are seeing this because you delete objects from a collection that currently has active operations on. More specifically you are updating the Kids collection and then executing the Any() operator on it in the while loop. This is not a supported operation when working with IEnumerable instances. What I can advice you to do is rewrite your while as this:

parent.Kids.ToList().ForEach(r => context.Kids.DeleteObject(r));

I hope that helps.

-1
votes

I had the same problem/error. The solution of ruffin worked.

this crashes :

var objectsToRemove = employee.Contracts.Where(m => ...);
objectsToRemove.ForEach(m => _context.Contracts.Remove(m));

this worked for me :

var objectsToRemove = employee.Contracts.Where(m => ...).ToList();
objectsToRemove.ForEach(m => _context.Contracts.Remove(m));