EF 1比1 .. *关系 [英] EF 1 to 1..* relationship

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

问题描述

是否可以在Entity Framework中创建一对一或多个关系?我已经看到很多例子显示1到0 .. *的关系,但是我想确保在给定的示例中Foo仅在至少具有一个Bar时才能存在。

Is there a way to create a one to one-or-more relationship in Entity Framework? I've seen plenty examples showing a 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; }
}

class Bar
{
    public Foo Foo { get; set; }
}

我看到这很难用SQL实现,因为我想要一种Foo表而不是Bar表的 NOT NULL 的值,但是Entity Framework可以处理吗?

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?


我意识到我问了一个错误的问题,因为我实际上是在寻找0..1到1 .. **的关系,这是非常不同的。 是我要问的问题。


推荐答案

在我所知道的任何SQL数据库中都不可能有真正的一对一关系。尽管Set理论允许实际为1到1,但这很难实现。

It's impossible to have a true 1 to 1 relationship in any SQL database that i'm aware of. While Set theory allows for a 1 to 1, in practicality, this is difficult to implement.

基本上是鸡和蛋的情况。您不能创建Foo,因为您没有Bar,也不能创建Bar,因为还没有Foo。创建1对1所需的约束实际上阻止了您插入任何实际的行。

It's basically a chicken and egg situation. You can't create Foo because you don't have a Bar, and you can't create Bar because there is no Foo yet. The constraints required to create a 1 to 1 essentially prevent you from inserting any actual rows.

现在,您可以禁用约束,插入数据,然后重新启用它们,但这确实是一个顽强的想法,但实际上却打败了约束的目的。

Now, you could disable constraints, insert the data and then re-enable them, but that's a hacky kludge that really defeat the purpose of having constraints in the first place.

所以只需接受1到0 .. *并继续。

So just accept the 1 to 0..* and move on.

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

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