I have to Entities A and B.
A has fields:
id (PK) and b_fk (FK to B's id).
B has similar fields:
id (PK) and a_fk (FK to A's id).
Now I want to create object A and B:
createAAndBMethod(Entities context){
A a = new A();
B b = new B();
a.b_fk = b;
b.a_fk = a;
context.As.AddObject(a);
context.Bs.AddObject(b);
}
someImportantMethod(){
//do sth
Entities context = new Entities(...);
//do sth, maybe some changes to db on context
createAAndBMethod(context);
//do sth, maybe some changes to db on context
context.SaveChanges();// <-- here I'm getting error
}
Saving doesn’t work with error: Unable to determine a valid ordering for dependent operations. Dependencies may exist due to foreign key constraints, model requirements, or store-generated values.
Is there any way to get this working with one save?
I need to create both objects in some code which shouldn’t be saving changes, so I can’t execute context.SaveChanges() anywhere before.
On context.SaveChanges() could happen something like:
Create newA with nulled field b_fk
Create newB with a_fk = newA
Set newA.b_fk to newB
Update:
both a_fk and b_fk are nullable. I’m working with MS SQL and Azure SQL.
Update2:
I changed createAAndBMethod(Entities context)to:
createAAndBMethod(Entities context){
A a = new A();
context.As.AddObject(a);
B b = new B();
a.b_fk = b;
}
But it still doesn’t work with same error.
I think you model has a problem; A table has a foreign key reference to B table; and B table has a foreign key reference to A table. Then why don’t you merge these tables and only create a single table?
If you are trying to create a one to one relationship, this is not the proper way.
UPDATE:
DB design is not proper. Only creating a foreign key in Table B is enough. there is no need to create a foreign key in Table A as such a design satisfies “A may have 0 or many Bs”.