当父记录已经存在时,首先使用Entity Framework代码,在子表中插入记录 [英] Insert record in child table when parent record already exists using Entity Framework code first

查看:79
本文介绍了当父记录已经存在时,首先使用Entity Framework代码,在子表中插入记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些父记录已经插入到数据库中。现在我想添加一些子记录。为此,我遵循以下步骤:


  1. 检索父母(A)记录

  2. 创建一个新生儿(B)记录

  3. 将父记录添加到导航属性的子。 BA = A

  4. 拨打SaveChanges。

问题是我做这个EF插入新建父,然后添加一个外键指向新的新插入的父项,而不是只插入子对象已存在的父对象。保存孩子时,我还检查了父级的主键,并且确实存在于数据库中。



请注意,我正在使用数据库生成的父母和孩子的身份。
有一件事我注意到,如果我从相同的上下文对象添加/保存Parent和Child,那么它工作正常。



需要修复这个asap。任何帮助将不胜感激。

解决方案

是的,您必须对该操作使用相同的上下文。这就是我想说的。如果您不使用相同的上下文,则必须手动控制将插入哪个对象,哪些更新,哪些不会被修改。在您的情况下,序列可以是:

  context.Parents.Attach(parent); //只是附加为不变
context.Childs.Add(child); //添加为插入
parent.Childs.Add(child); //使现有和插入对象之间建立连接
context.SaveChanges();

另一种方法可以是:

  child.Parent = parent; 
context.Childs.Add(child); //孩子和父母都被标记为插入!
context.Entry(parent).State = EntityState.Unchanged; //将父项设置为未更改
context.SaveChanges();


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:

  1. Retrieve the Parent(A) records
  2. Create a new child(B) record
  3. Add parent record to the Navigation property of Child. B.A = A
  4. Call SaveChanges.

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();

这篇关于当父记录已经存在时,首先使用Entity Framework代码,在子表中插入记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆