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

I have two tables that are nn related. 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 do not try to change obj1.Table2 , it automatically joins and saves. But if I try to change this EntityCollection

 element.Table2.Add(tb2); 

And save, I get the following error:

An object with a temporary EntityKey value cannot be bound to the object context.

in line: database.Attach(element);

How can i fix this?


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 the 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
c # entity-framework entity-relationship
source share
1 answer

enter image description here

If your working Entity frame model is set something like this, you should be able to change t1 or t2 without any problems. while maintaining

From the look of table 3 in your example, you don't have a key for the entries. This will cause problems when modifying an Entity object. Which DB Fk you have installed.

+2
source share

All Articles