2015-02-23 58 views
1
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一个小问题,当涉及到如下因素的情况时,节能方面的变化:EF增加了另一个入口,即使它存在

我加了一个家长带一个孩子,但如果我提取Child c (与c.Parent == null),然后它的Parent p(2个查询),然后执行:

Child.Parent = p; 
context.SaveChanges(); 

它将即使p存在数据库中添加一个新的Parent。有没有办法来覆盖这种行为?

回答

2

也许你正在与分离的实体合作。如果您没有从您的背景的同一实例中获取父实体,那么当您将Parent指定给Child实例时,EF认为这是一个无法识别的实体,并且其对于无状态的未识别实体的默认行为是将它们标记为Added。因此,当调用SaveChanges时,Parent将再次插入到数据库中。

要解决这个问题,试试这个:

context.Parents.Attach(p); 
Child.Parent = p; 
context.SaveChanges(); 

另外,代替context.Parents.Attach(p),你可以设置Parent状态的事实之前或之后,其状态明确设置为Unchanged

context.Entry(p).State = EntityState.Unchanged; 

如果您想了解更多关于此主题的信息,我建议您阅读此article

相关问题