EF 5 - 收藏被修改;枚举操作可能无法执行

时间:2012-09-23 19:34:49

标签: c# .net entity-framework dbcontext entity-framework-5

我想使用Entity Framework 5将一些测试数据插入到我的数据库中。只有当我取消注释 1行代码时才能正常工作:

var query = DbContext.Set<User>().AsQueryable();
query = query.Include("Tabs.Boxes");
query = query.Where(u => u.Name == "test_guy");
User test_guy = query.Single();

Tab mainTab = new Tab() 
{ 
    TabName = "Main tab",
    Order = 1,
};
Tab otherTab = new Tab()
{
    TabName = "Test Guy's another tab",
    Order = 2
};

test_guy.Tabs.Add(mainTab);
test_guy.Tabs.Add(otherTab);

DbContext.SaveChanges();   // --> If I comment this out, everything breaks!

mainTab.Boxes = new Boxes();
for (int i = 0; i < 10; i++)
{
    Box box1 = new Box()
    {
        Author = test_guy
    };
    mainTab.Boxes.Add(box1);
}

DbContext.SaveChanges();

如果我注释,SaveChanges会调用,我会收到异常: Collection was modified; enumeration operation may not execute.

我只是想知道,这种行为的原因是什么?

2 个答案:

答案 0 :(得分:0)

在将mainTab添加到test_guy之前尝试向mainTab添加框,并且只有一次调用savechanges()方法,如下所示:

var query = DbContext.Set<User>().AsQueryable();
query = query.Include("Tabs.Boxes");
query = query.Where(u => u.Name == "test_guy");
User test_guy = query.Single();

Tab mainTab = new Tab() 
{ 
    TabName = "Main tab",
    Order = 1,
};
Tab otherTab = new Tab()
{
    TabName = "Test Guy's another tab",
    Order = 2
};

mainTab.Boxes = new Boxes();
for (int i = 0; i < 10; i++)
{
    Box box1 = new Box()
    {
        Author = test_guy
    };
    mainTab.Boxes.Add(box1);
}

test_guy.Tabs.Add(mainTab);
test_guy.Tabs.Add(otherTab);

DbContext.SaveChanges();  

答案 1 :(得分:0)

我有同样的例外 - 在我的情况下,原因是在dbModel上重复关联。