[英]Prevent Entity Framework from creating foreign key in database
我有一個代碼優先的數據庫,其中包含以下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; }
}
這將在數據庫中創建以下表:
富
FooId (PK, int, not null)
Bar_BarId (FK, int, null)
酒吧
BarId (PK, int, not null)
DefaultFoo_FooID (FK, int, null)
FooBar的
Bar_BarId (PK, FK, int, not null)
Foo_FooId (PK, FK, int, not null)
正如你可以看到Foo
表得到一個外鍵關系到Bar
表即使Foo
POCO沒有一個到一個導航屬性到Bar
POCO。
但是,如果我從Bar
刪除DefaultFoo
屬性,則會刪除此外鍵。
而且,如果我將DefaultFoo
保留在其中,但從Foo
刪除了Bars
,而從Bar
刪除了Foos
,則會刪除此外鍵。
換句話說,僅當Bar
上同時存在DefaultFoo
和Foos
才存在此外鍵。
如何使Entity Framework 不創建此不必要的外鍵(最好不使用FluentApi)?
我的猜測是:
我沒有/不能說為什么。
但是對我來說,您必須使用一些配置方法來幫助恢復默認行為:流利的或批注以顯式設置多/多關系。
您可以使用linqpad挑戰它,並檢查生成的sql中是否存在某些查詢。
我嘗試您的模型,並且未創建交匯表(FoosBars)。 創建的列是為2個1-many Foo.Bars和Bar.Foos屬性以及1-1 Bar.DefaultFoo創建的。
我認為在這種情況下,唯一的方法是使用HasMany / WithMany流利的API配置nm關系。 在這種情況下,EF會按預期工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.