The Entity Framework Collection has been changed, and the enumeration procedure may no longer operate.

c# entity-framework

Question

Right now, I'm using EF 4.0. My goal is to remove a group of children and add new ones to the 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 reads, "Collection was updated; enumeration operation may not perform," as stated in the headline.

We would appreciate any assistance.

1
26
2/23/2012 2:44:19 AM

Accepted Answer

You are seeing this as a result of the deletion of items from a collection that still contains open operations. In the while loop, you are explicitly updating the Kids collection and using the Any() operator on it. When dealing with IEnumerable objects, this operation is not supported. What I can suggest is that you modify your sentence as follows:

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

Hope that was helpful.

48
2/23/2012 9:54:28 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow