[英]Prevent Entity Framework from creating foreign key in database
I have a code-first database with the following POCOs: 我有一个代码优先的数据库,其中包含以下POCO:
public Foo {
public int FooId { get; set; }
public virtual ICollection<Bar> Bars { get; set; }
}
public Bar {
public int BarId { get; set; }
public virtual Foo DefaultFoo { get; set; }
public virtual ICollection<Foo> Foos { get; set; }
}
This creates the following tables in the database: 这将在数据库中创建以下表:
Foo 富
FooId (PK, int, not null)
Bar_BarId (FK, int, null)
Bar 酒吧
BarId (PK, int, not null)
DefaultFoo_FooID (FK, int, null)
FooBar FooBar的
Bar_BarId (PK, FK, int, not null)
Foo_FooId (PK, FK, int, not null)
As you can see the Foo
table gets a foreign key relation to the Bar
table even if the Foo
POCO does not have a one-to-one navigation property to the Bar
POCO. 正如你可以看到
Foo
表得到一个外键关系到Bar
表即使Foo
POCO没有一个到一个导航属性到Bar
POCO。
However, if I remove the DefaultFoo
property from Bar
this foreign key is removed. 但是,如果我从
Bar
删除DefaultFoo
属性,则会删除此外键。
And, if I leave DefaultFoo
in, but remove Bars
from Foo
and Foos
from Bar
this foreign key is removed. 而且,如果我将
DefaultFoo
保留在其中,但从Foo
删除了Bars
,而从Bar
删除了Foos
,则会删除此外键。
In other words, this foreign key is only present if both DefaultFoo
and Foos
is present on Bar
. 换句话说,仅当
Bar
上同时存在DefaultFoo
和Foos
才存在此外键。
How can I make Entity Framework not create this unneccessary foreign key (preferrably without using FluentApi)? 如何使Entity Framework 不创建此不必要的外键(最好不使用FluentApi)?
my guess is: 我的猜测是:
I do not/can not say why. 我没有/不能说为什么。
But For me you have to help de default behavior by using some configuration method: fluent or annotations to explicitly set the many/many relation. 但是对我来说,您必须使用一些配置方法来帮助恢复默认行为:流利的或批注以显式设置多/多关系。
You can challenge that by using linqpad and check the generated sql for some queries. 您可以使用linqpad挑战它,并检查生成的sql中是否存在某些查询。
I try your model and Junction table (FoosBars) is not created. 我尝试您的模型,并且未创建交汇表(FoosBars)。 The columns created is for the 2 1-many Foo.Bars and Bar.Foos properties and for the 1-1 Bar.DefaultFoo.
创建的列是为2个1-many Foo.Bars和Bar.Foos属性以及1-1 Bar.DefaultFoo创建的。
I think that in this case the only way is to configure nm relationship using HasMany/WithMany fluent API. 我认为在这种情况下,唯一的方法是使用HasMany / WithMany流利的API配置nm关系。 In this case EF works as expected.
在这种情况下,EF会按预期工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.