Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 291
BrunoLM Avatar asked Mar 03 '11 14:03

BrunoLM


People also ask

Which method is used to reattach an object?

session. lock() method is used to reattach a detached object to the session. session.

How would you reattach detached object to a session?

The lock() method also allows an application to reassociate an object with a new session. However, the detached instance has to be unmodified! //just reassociate: sess.

What is a one-to-many relationship?

A one-to-many relationship exists in a relational database when one row in table A is linked to many rows in table B, but only one row in table B is linked to one row in table A. It's vital to remember that a one-to-many relationship is the quality of the relationship, not the data.


1 Answers

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.

like image 167
Dimentox Avatar answered Oct 06 '22 01:10

Dimentox