0

I'm trying to query a data table called "Nations" from a DataContext object and receive the following exception when calling SubmitChanges():

Collection was modified; enumeration operation may not execute

Below is a snippet of the code:

foreach (Nation thisNation in NationList)
{
    Nation nation = nationDB.Nations.Where(c => c.ID == thisNation.ID).First();
    nation.Duplicate(thisNation);
}

Where Duplicate() is a method that copies some properties of a Nation object:

I'm using EF with CTP5.

What am I doing wrong?

apaderno
  • 28,547
  • 16
  • 75
  • 90
Francesco
  • 964
  • 2
  • 17
  • 41
  • 2
    Just by looking at it, this should work, can you expand the code snipped a bit to include the implemenation of `Duplicate()` and `SaveChanges()` ? – BrokenGlass Mar 21 '11 at 18:02

2 Answers2

4

Though not directly evident here, the problem is usually that you're using foreach which can only enumerate the items, and will not allow you to manipulate the collection directly. The approach probably gets a little more temperamental when Linq is involved.

You could replace what you have with a simple for loop which should solve the problem - however, this does open up another potential problem should you not address it: you will need to manage the current index which is automatically incremented/decremented by the for, lest you'll get 'off-by-x issues'.

Grant Thomas
  • 44,454
  • 10
  • 85
  • 129
  • I'm still getting this problem even if I tried to use both yours and AJ approach... – Francesco Mar 21 '11 at 21:04
  • You say the issue occurs on `SaveChanges` and the snippet here doesn't show us the collection being modified - okay, can we see some more code? – Grant Thomas Mar 21 '11 at 21:10
  • The Class Nation has fields: int ID, string name, List regions. The method Duplicate is copying every field one by one. – Francesco Mar 21 '11 at 21:24
  • I modify the nationDB.Nations collection by copying the values from nationList to the collection. This should be affecting the Database, right? – Francesco Mar 21 '11 at 21:38
  • Even a simpler syntax, like nation.name = "test" in the foreach loop is throwing the exception when I call SubmitChanges – Francesco Mar 21 '11 at 21:45
  • I think I solved the problem. Before the code snippet I was executing a number of operations against the nationDB. In one of these operations I was adding to nationDB some of the objects contained in the collection NationList and then calling SaveChanges. – Francesco Mar 22 '11 at 12:18
1

This is the "modified closure" demon. Try doing this instead:

foreach (Nation thisNation in NationList)
{
    var tempNation = thisNation;
    Nation nation = nationDB.Nations.Where(c => c.ID == tempNation.ID).First();
    nation.Duplicate(tempNation);
}

Good post here with more information.

AJ.
  • 16,368
  • 20
  • 95
  • 150