0

I want to insert some test data into my database with Entity Framework 5. It works fine - only if I uncomment 1 line of code:

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();

If I comment out that SaveChanges call, I will get an exception: Collection was modified; enumeration operation may not execute.

I just want to know, what is the reason for this behaviour?

4

2 に答える 2

0

以下に示すように、mainTabをtest_guyに追加する前に、ボックスをmainTabに追加して、savechanges()メソッドを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
};

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();  
于 2012-09-23T23:30:13.097 に答える
0

私は同じ例外を抱えていました - 私の場合、その理由はdbModelの関連付けの重複にありました。

于 2012-10-04T13:52:19.390 に答える