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?
Though not directly evident here, the problem is usually that you’re using
foreachwhich 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
forloop 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 thefor, lest you’ll get ‘off-by-x issues’.