"The relationship between these two objects cannot be defined because they are attached to a different ObjectContext object", which is an error that occurs in EF, a one-to-many relational table that has foreign key classes saved to the database.
I used to be developed in Java, the habitual processing of a pair of multi-class and the relationship between the class, in C # is also handled. The following is a simple one-to-many relationship in C # implementation (first database, post vs generate Code):
Public classobjecta{ Public intid{Set;Get;} Public intobjectbid{Set;Get;}//Database Generation PublicOBJECTB b{Set;Get;}//vs Auto-implementation} Public classobjectb[ Public intid{Set;Get;} //There's probably a Objecta collection.}
In the business logic, it is customary to find a OBJECTB and then assign values in the following form:
public class formnew:form{ > ... Omit other code public void button1_click (object sender, EventArgs e) {OBJECTB b = XXB (); // query by other methods Objecta a = new Objecta (); A.B = B; XXA. Save (a); // save A, This will be reported above the exception !!!
In the online query, the explanation is probably the previous call Xxb method DbContext and Xxa.save () DbContext inconsistent. The specific principle I also do not understand (novice), let me very can not understand is, this class storage ID, should be consistent, how do not let save it!!
But we have to find a way to solve the problem. After I test, do not use the above relationship to the corresponding form, and the following method can be resolved:
Public classformnew:form{//... Omit other code Public voidButton1_Click (Objectsender, EventArgs e) {OBJECTB B= XXXXX ();//querying by other meansObjecta A =Newobjecta (); A.objectbid= b.ID;//This only adjusts the field values of the foreign key set in the database and does not maintain the relationshipXxxxx. Save (a);//save a with dbcontext and then maintain the relationship }} Public classxxxxx{ Public voidSave (Objecta a) {DBContext db=NewDBContext ();//here is the hypothetical, by means of obtaining dbcontextOBJECTB B = Db.objectb.where("...");//query B with DbContextA.B = b;//then the assignment is no problem, query OBJECTB with the DbContext and save Objecta with the DbContext is the same. Db.objecta.AddObject (a); } }
I don't know if I'm clear about my idea. Leave a memorial, after the problem, and then look.
EF data storage Problem Two "the relationship between these two objects cannot be defined because they are attached to different ObjectContext objects"