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

I have some parent records already inserted into the database. Now I want to add some child entries. To do this, I have completed the following steps:

  • Get Parent Entries (A)
  • Create a new baby record (B)
  • Add a parent entry to the Navigation Child property. BA = A
  • Call SaveChanges.

The problem is when I do this EF, inserts a new parent, and then adds the child with a foreign key pointing to the new newly inserted parent, instead of only inserting the child with the mapping into the already existing parent. I also checked the parent primary key while saving the child, and it exists in the database.

Please note that I am using the database identifier for the parent and child. One thing I noticed is adding / Save the parent and child from the same context object, then it works fine.

You need to fix it as soon as possible. Any help would be greatly appreciated.

+6
source share
3 answers

Yes, you must use the same context for this operation. That's the problem. If you are not using the same context, you must manually control which object will be inserted, which is updated and which will not be modified. In your scenario, the sequence could 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 could 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(); 
+19
source

Also, in case 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 into the existing ID record in the database and leave ParentA null, and on context.SaveChanges() it will work as expected (without creating another A record in the database).

0
source

The code below works 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. 
0
source

Source: https://habr.com/ru/post/894112/


All Articles