I have some Parent records already inserted in the database. Now i want to add some child records. To do this I followed following steps:
The problem is when i do this EF inserts a New Parent and then add the child with a foreign key pointing to new newly inserted parent instead of inserting just the child with mapping to already existing parent. I also checked the parent's primary key when saving the child and it does exists in the database.
Note that i am using database generated identity for Parent and Child. One thing i noticed was if I add/Save Parent and Child from the same context object then it works fine.
Need to fix this asap. Any help will be greatly appreciated.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With