集合已被修改的异常 [英] Collection was modified exception

查看:50
本文介绍了集合已被修改的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从 DataContext 对象查询名为"Nations"的数据表,并在调用 SubmitChanges()时收到以下异常:

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

下面是代码段:

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

其中 Duplicate()是一种复制 Nation 对象的某些属性的方法:

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

我将EF与CTP5配合使用.

I'm using EF with CTP5.

我在做什么错了?

推荐答案

虽然在这里没有直接显示,但问题通常是您使用的是 foreach ,它只能枚举项目,而不会允许您直接操作集合.当涉及Linq时,该方法可能会变得有点气质.

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.

您可以用一个简单的 for 循环替换现有的内容,这可以解决问题-但是,如果您不解决此问题,这确实会带来另一个潜在的问题:您将需要管理当前索引它会由 for 自动递增/递减,以免出现"off-by-x的问题".

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'.

这篇关于集合已被修改的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆