Entity Framework Fluent Mapping Optional One-To-One

本秂侑毒 提交于 2019-12-04 19:25:56

A common way to model an optional 1 : 1 association is (in FooMap)

HasOptional(f => f.Bar).WithRequired(b => b.Foo);

But it does not produce the model you want. It does not need Foo.BarId, because Bar.BarId is both a primary key and a foreign key to Foo.FooId.

If you'd have Foo.BarId it should have a unique constraint to ensure that it is only used once in a FK association. So you might as well use the already available unique field, the primary key.

EDIT

It was not clear to me that you wanted both sides of the association to be optional. You can achieve that by (in BarMap):

HasOptional(b => b.Foo).WithOptionalPrincipal(f => f.Bar)
                       .Map(m => m.MapKey("BarId"));

This brings you the data model you showed in your post.

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