我必须实体A
和B
.
A
有字段:
id
(PK)和b_fk
(FK到B's id
)。
B
具有相似的字段:
id
(PK) 和a_fk
(FK to A's id
)。
现在我想创建对象A
和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
}
保存不起作用并出现错误:Unable to determine a valid ordering for dependent operations. Dependencies may exist due to foreign key constraints, model requirements, or store-generated values.
有什么办法可以通过一次保存来解决这个问题吗?我需要在一些不应该保存更改的代码中创建这两个对象,所以我context.SaveChanges()
之前无法在任何地方执行。
Oncontext.SaveChanges()
可能会发生类似的事情:
Create newA with nulled field b_fk
Create newB with a_fk = newA
Set newA.b_fk to newB
更新:两者a_fk
都可b_fk
以为空。我正在使用 MS SQL 和 Azure SQL。
更新2:我改为createAAndBMethod(Entities context)
:
createAAndBMethod(Entities context){
A a = new A();
context.As.AddObject(a);
B b = new B();
a.b_fk = b;
}
但它仍然无法使用相同的错误。