【发布时间】:2016-09-06 09:15:24
【问题描述】:
我有一个包含以下 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; }
}
这会在数据库中创建以下表:
Foo
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,则此外键将被删除。
换句话说,只有当DefaultFoo 和Foos 都出现在Bar 上时 才会出现这个外键。
如何让实体框架不创建这个不必要的外键(最好不使用 FluentApi)?
【问题讨论】:
-
您能描述一下您想要实现的目标吗?在 Bar 上拥有 Multiple-和 Single- Foo 属性对我来说没有意义。此外,通过给 Bar 一个 Foo 类型的属性,您可以在这些类上建立一对一的关系。
-
您可以尝试在 Bar 类中添加
public in SingleFooId{get;set};并装饰导航属性[ForeignKey("SingleFooId")]public virtual Foo SingleFoo { get; set; } -
@J.Swietek 一个
Bar可以有多个Foo,但其中一个Foos 是默认值。这样当Bar上有许多Foos 时,如果没有特别指定,您就知道使用哪一个。我已将模型编辑为默认而不是 Single 以(希望)使其更清晰。
标签: c# .net entity-framework entity-framework-6