EF记录更新为相关对象创建新记录 [英] EF record update creates new record for related object
本文介绍了EF记录更新为相关对象创建新记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个EntityFramework代码第一个项目,其中两个对象之间的宽度关系。
I have an EntityFramework code first project with two objects width a relationship.
代码示例:
public class A{
public int ID{get;set;}
public B b{get;set;}
}
当我打电话时:
_context.A.Attach(a);
_context.Entry(a).State = EntityState.Modified;
_context.SaveChanges();
我成功更新了A,但是在表B中获得了新记录。
I successfully update A but i get a new record in table B.
如何避免这种情况,以便我在更新A时也更新B而不创建av新对象?
How can i avoid this so that when i update A i also update B not createing av new one?
推荐答案
我不会以这种方式在分离的上下文中执行操作—容易出错—但是在附加上下文中解决类似问题的方法是 Include
:
I don't do things in a detached context this way — it's error prone — but the solution for similar things in an attached context is an Include
:
using (var context = new Context())
{
context.A.Include(a => a.B).Attach(a);
context.Entry(a).State = EntityState.Modified;
context.SaveChanges();
}
这篇关于EF记录更新为相关对象创建新记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文