我想使用 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.
我只想知道,这种行为的原因是什么?