Insert record in child table when parent record already exists using Entity Framework code first

天大地大妈咪最大 提交于 2019-11-29 02:28:58

Yes you must use the same context for that operation. That is the point. If you don't use the same context you must manually control which object will be inserted, which updated and which will not be modified. In your scenario the sequence can be:

context.Parents.Attach(parent); // just attach as unchanged
context.Childs.Add(child); // add as inserted
parent.Childs.Add(child); // make connection between existing and inserted object
context.SaveChanges();

Another approach can be:

child.Parent = parent;
context.Childs.Add(child); // both child and parent are marked as inserted!!!
context.Entry(parent).State = EntityState.Unchanged; // set parent as unchanged
context.SaveChanges();

Also, in the case when you have something like:

public class B
{
[Key]
public int Id {get;set;}

public AId {get;set;}

//... other properties here

[ForeignKey("AId")]
public virtual A ParentA {get;set;}
}

you could only set the foreign key to the existing A id entry in DB without and leave the ParentA null and on context.SaveChanges() it will work as expected (not creating another A entry in DB).

Rameshkumar

The below code worked for this situation.

networkDbo.Form.Id = forms.Id; // <-- AGAIN assigning FK  // Form is Parent Table 
this.dbContext.Form.Attach(formsdbo);  // Attach the parent value to db Context
this.dbContext.Network.Attach(networkDbo); // network is Child 
this.dbContext.Entry(networkDbo).State = EntityState.Added;  // Entity State is Added.
this.dbContext.SaveChanges();  // Save the Db context.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!