public class Parent
{
public int ID;
public string Name;
public int Child_ID;
public Child Child;
}
public class Child
{
public int ID;
public string Name;
public int Parent_ID;
public Parent Parent;
}
在涉及到下列情况时,我对ef有一点问题:
我添加了一位有孩子的父母,但是如果我提取Child c
(带有c.Parent == null
)然后是Parent p
(2个查询)然后执行:
Child.Parent = p;
context.SaveChanges();
即使Parent
存在,它也会在数据库中添加新的p
。有没有办法覆盖这种行为?
答案 0 :(得分:2)
可能您正在使用分离的实体。如果您从同一个constext实例中获取父实体,则在将Parent
分配给Child
实例时,EF认为这是一个无法识别的实体及其默认行为没有状态的无法识别的实体将它们标记为Added
。因此,再次,Parent
将在调用SaveChanges
时插入到数据库中。
要解决该问题,请尝试以下操作:
context.Parents.Attach(p);
Child.Parent = p;
context.SaveChanges();
或者,代替context.Parents.Attach(p)
,您可以在事实之前或之后设置Parent
的状态,明确将其状态设置为Unchanged
:
context.Entry(p).State = EntityState.Unchanged;
如果您想了解有关此主题的更多信息,建议您阅读此article