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

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