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 | 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
6
задан BrunoLM 3 March 2011 в 14:44
поделиться