6

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
BrunoLM
  • 97,872
  • 84
  • 296
  • 452
  • How did you create tb2? Where did you call Table2.Add(tb2)? – Ladislav Mrnka Mar 03 '11 at 14:25
  • @Ladislav, a method that creates a context and returns the object. `GetTable2Obj(id)` = `using (var database ...) { return database.Table2.Where(o => o.ID == id).FirstOrDefault(); }` – BrunoLM Mar 03 '11 at 14:40
  • But your added code should not attach the element. It should use AddObject because the Id is set to 0. Anyway M:N with detached entitites is the pain. Check my answer here: http://stackoverflow.com/questions/3635071/update-relationships-when-saving-changes-of-ef4-poco-objects/3635326#3635326 – Ladislav Mrnka Mar 03 '11 at 14:46
  • @Ladislav: Acually it exists. I screwed the example trying to make the question more generic. But I fixed, I also retrieve it from a method. (`GetTable1Obj`) – BrunoLM Mar 03 '11 at 14:49
  • Your methods GetTableXObj don't matter - you are still working with detached entities because each method uses its own context. But I have to say your exception message probably points to another problem. – Ladislav Mrnka Mar 03 '11 at 14:51

1 Answers1

2

enter image description here

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.

Dimentox
  • 189
  • 6