不确定如何修复这个奇怪的实体框架(关系/导航)错误
当我尝试使用实体框架作为 OR/M 保存 poco 实体时,我不断收到以下错误消息:-
<块引用>“SqlServerContext.Foos”中的实体参与“FK_Foos_Bahs”关系。找到 0 条相关“呸”。 1 应为“Bah”。
好的 - 错误消息是有道理的 - 但这不是我建模的:((或正在尝试建模)。它是说,如果我想保存 Foo
,那么我需要 1 个实例Bah
可以在没有 Bah
的情况下存在。关系应该是 1 <-> 0-or-1。
.. 不是 1 <-> 1
.
这是 EF 中的模型 ...
任何人都可以看看我做错了什么?
I keep getting the following error message when i try to save a poco entity, using Entity Framework as the OR/M :-
Entities in 'SqlServerContext.Foos' participate in the 'FK_Foos_Bahs' relationship. 0 related 'Bah' were found. 1 'Bah' is expected.
Ok - the error message makes sense -- but that is NOT what I modeled :( (or am trying to model). It's saying that if I wish to save a Foo
, then I need 1 instance of a Bah
. A Foo
can exist without a Bah
. The relationship should be 1 <-> 0-or-1
.. not 1 <-> 1
.
Here's the model in EF ...
Can anyone see what I've done wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你的模型可能是错误的。目前您说
Bah
是许多Foos
的主要实体。这是一对多的关系,而不是一对一的关系。此外,您在Foo
中将Bah
定义为强制,因为Bah
上的多重性是 1 而不是 0..1 。Your model is probably wrong. At the moment you are saying that
Bah
is principal entity of manyFoos
. It is one-to-many relation not one-to-one. Also you definedBah
as mandatory inFoo
because multiplicity onBah
is 1 not 0..1.看起来您的关系是从后到前的 - 您的屏幕截图显示 1 Bah 有许多 Foo,而 Foo 正好有 1 Bah - 听起来您需要交换两端,以便 1 Foo 可以有许多 Bahs 并且 Bah 正好有 1 Foo 。
您还可以执行 0...1 到多个关系(每个 Bah 可以有许多 Foo,Bah 有 0 或 1 个 Foo),或 0...1 到 1 关系。 .Net 将在数据库中创建可为空的字段,并在模型中创建可为空的属性,并且您将可以在没有关联的情况下保存数据。
我知道您可能正在处理敏感数据,因此会被删除,但也许如果您将其替换为更有意义的假数据,可能会更容易理解您想要做什么! Foo 和 Bah 的演示不如“人”和“宠物”或“爱好”等同样干净的东西直观。
Looks like your relationship is back to front - your screen grab shows that 1 Bah has many Foos and Foo has exactly 1 Bah - it sounds like you need to swap the ends round so that 1 Foo can have many Bahs and Bah has exactly 1 Foo.
You can also do 0...1 to many relationships (each Bah can have many Foos, Bahs have 0 or 1 Foo), or 0...1 to 1 relationships. .Net will make nullable fields in the database and nullable properties in your model, and you'll be allowed to save data without the associations.
I know you're probably working with sensitive data hence the blanking out, but maybe if you swapped it to a more meaningful fake it'd be easier to understand what you're trying to do! Foo and Bah make a less intuitive demonstration than something equally sanitised like People and Pets or Hobbies or whatever.