EF 0..1〜1 .. *关系 [英] EF 0..1 to 1..* relationship

查看:175
本文介绍了EF 0..1〜1 .. *关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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
}

我看到这不容易实现由SQL因为我在Foo表而不是在Bar表中想要一种 NOT NULL ,而是可以实体框架处理这个?

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?

推荐答案

如果我错了,请更正我,但我想你想要这样的东西:

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);

这篇关于EF 0..1〜1 .. *关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆