开发者

How to attach an object that contains a n to n relation?

I have two tables that are linked n-n. And I have a method that takes one object and saves.

public int Save(Table1 element)
{
    using (var database = new Entities())
    {
        if (element.ID == 0)
        {
            database.Table1.AddObject(element);
        }
        else
        {
            database.Attach(element); //
            database.ObjectStateManager.GetObjectStateEntry(element).SetModified();
            database.Refresh(RefreshMode.ClientWins, element);
        }

        return database.SaveChanges();
    }
}

When I don't try to modify obj1.Table2 it attaches and saves successfully. But if I try to modify this EntityCollection

element.Table2.Add(tb2);

And save, I get the following error:

An object with a temporary EntityKey value cannot be attached to an object context.

at Line: database.Attach(element);

How can I fix it?


Database:

Table 1             Table 2
ID | Name           ID |开发者_StackOverflow Name
---------           -------------------
 1 | One             1 | Related to One
 2 | Two             2 | Related to One
 3 | Three

            Table 3
            Tb1 | Tb2
            ---------
//            1 | 1
//            1 | 2

Creating Table1 object:

var element = GetTable1Obj(1);

element.Table2.Add(GetTable2Obj(1)); // GetTable2Obj uses a separated context
element.Table2.Add(GetTable2Obj(2)); // like Save method to return the object

provider.Save(element); // Method above


How to attach an object that contains a n to n relation?

If Your Entity frame work model is set to something like this You should be able to modify t1 or t2 without having issues. while still keeping

From the looks of table 3 in your example you don't have a key for the entries. Which will cause issues when modifying the Entity Object. What is your DB Fk set at.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜