如果我有一個 Parent 對象,其中包含對 Child 表的外鍵引用,并且我向 Parent 添加了一個 Child,我是否需要分別在 Child 和 Parent 上調用 Context.Add() ?或者只是父母?鑒于:Parent.childobj=child;//foreign key reference set to the child object這個:mycontext.Add(Child);
mycontext.Add(Parent);或者mycontext.Add(Parent);
1 回答

拉莫斯之舞
TA貢獻1820條經驗 獲得超10個贊
如果兩個實體都已經存在并且您想要將子實體與父實體相關聯,并且父實體也被上下文跟蹤,則更新 FK 屬性就足夠了。
Parent.ChildId=child.Id;
context.SaveChanges();
現在如果Child是一個新實體并且父實體已經存在并且已經被上下文跟蹤,那么使用引用屬性將兩者關聯起來:
Parent.childobj=child; // You can also do this if both exist already in your DB
context.SaveChanges();
如果兩者都是新的,則將父項添加到上下文中,這也將保留相關的子項:
Parent.childobj=child;
context.Parent.Add(parent);
context.SaveChanges();
- 1 回答
- 0 關注
- 120 瀏覽
添加回答
舉報
0/150
提交
取消