EF 0..1到1 .. *关系

时间:2017-06-14 07:54:18

标签: entity-framework ef-code-first

有没有办法在Entity Framework中创建零或一对一或多关系?我已经看到很多示例显示0..1到0 .. *的关系,但我想确保在给定的示例中,只有Foo至少有一个Bar才能存在。

class Foo
{
   List<Bar> Bars { get; set; } // Must at least have one Bar
}

class Bar
{
    public Foo Foo { get; set; } // Foo is nullable
}

我发现SQL不容易实现这一点,因为我想在Foo表而不是Bar表中使用NOT NULL,但实体框架可以处理吗?

1 个答案:

答案 0 :(得分:0)

如果我错了,请纠正我,但我认为你想要这样的事情:

modelBuilder.Entity<Foo>() 
    .HasMany(t => t.Bars) 
    .WithOptionalPrincipal(t => t.Foo);
相关问题