开发者

Collection was modified exception

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 no开发者_开发知识库t 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 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'.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜