C# 实体框架集合被修改;枚举操作可能不会执行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9406088/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 07:14:45  来源:igfitidea点击:

Entity Framework Collection was modified; enumeration operation may not execute

c#entity-framework

提问by madatanic

I'm currently using EF 4.0. My objective is to delete a child collection and add new ones to same parent.

我目前正在使用 EF 4.0。我的目标是删除一个子集合并将新集合添加到同一个父集合。

 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 is as from the title: Collection was modified; enumeration operation may not execute.

错误来自标题:Collection was modified; 枚举操作可能无法执行。

Any help would be appreciated.

任何帮助,将不胜感激。

采纳答案by ScorpiAS

You are seeing this because you delete objects from a collection that currently has active operations on. More specifically you are updating the Kids collection and then executing the Any() operator on it in the while loop. This is not a supported operation when working with IEnumerable instances. What I can advice you to do is rewrite your while as this:

您之所以看到这一点,是因为您从当前具有活动操作的集合中删除了对象。更具体地说,您正在更新 Kids 集合,然后在 while 循环中对其执行 Any() 运算符。使用 IEnumerable 实例时,这不是受支持的操作。我可以建议您做的是将您的 while 改写为:

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

I hope that helps.

我希望这有帮助。