问题描述
是否可以在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?
推荐答案
在我所知道的任何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 .. *关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!