EF 0..1 to 1..* relationship

穿精又带淫゛_ 提交于 2019-12-13 02:57:53

问题


Is there a way to create a zero-or-one to one-or-many relationship in Entity Framework? I've seen plenty examples showing a 0..1 to 0..* relationship, but I want to be sure that in the given example Foo can only exist if it has at least one Bar.

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

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

I see that this is not easily achieved by SQL since I want a kind of NOT NULL at the Foo table instead of at the Bar table, but can Entity Framework handle this?


回答1:


Correct me if i'm wrong, but I think you want something like this:

modelBuilder.Entity<Foo>() 
    .HasMany(t => t.Bars) 
    .WithOptionalPrincipal(t => t.Foo);


来源:https://stackoverflow.com/questions/44538745/ef-0-1-to-1-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!