EF插入重复的父对象

mat*_*wen 5 entity-framework

我有两节课:

public class Foo
{
    public int FooId {get;set;}
    public virtual ICollection<Bar> Bars {get;set;}
}

public class Bar
{
    public int BarId {get;set;}
    public virtual Foo {get;set;}
}
Run Code Online (Sandbox Code Playgroud)

如果我运行以下代码,我会得到一个Foreign Key ConflictFooId.

var foo = from f in context.Foos
          where f.FooId == 1
          select f;

var bar = new Bar();
bar.Foo = foo;

context.Bars.Add(bar);
context.SaveChanges();
Run Code Online (Sandbox Code Playgroud)

如果我在SQL中禁用所有密钥检查,我最终会Foo在数据库中出现重复.

Sla*_*uma 1

使用foo与添加新内容相同的bar上下文加载foo不会导致重复。我的猜测是您的真实代码使用两个不同的上下文。

代码中唯一需要更改的内容(不会编译,因为foo是 anIQueryable<Foo>而不是 a Foo)是具体化foo,例如:

var foo = (from f in context.Foos
          where f.FooId == 1
          select f).Single();
Run Code Online (Sandbox Code Playgroud)

除此之外,代码片段很好。