问题描述
我有两个类:
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;}
}
如果运行以下代码,则会得到 FooId上的外键冲突
。
If I run the following code, I get a Foreign Key Conflict
on FooId.
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();
如果禁用SQL中的所有键检查,最终将得到重复的 Foo
在数据库中。
If I disable all the key checks in SQL, I end up with a duplicate Foo
in the database.
推荐答案
加载 foo
和相同上下文,即添加新的栏
和相关的 foo
不会造成重复。我的猜测是您的实际代码使用了两种不同的上下文。
Loading the foo
with the same context as adding the new bar
with the related foo
won't cause a duplication. My guess is that your real code uses two different contexts.
唯一需要更改的代码(由于 foo
是 IQueryable< Foo>
,而不是 Foo
)是要实现 foo
,例如:
The only thing to change in the code (which won't compile because foo
is an IQueryable<Foo>
and not a Foo
) is to materialize the foo
, for example:
var foo = (from f in context.Foos
where f.FooId == 1
select f).Single();
除了代码段还不错之外。
Other than that the code snippet is fine.
这篇关于EF插入重复的父对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!