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
session. lock() method is used to reattach a detached object to the session. 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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With