Entity Framework Fluent Mapping Optional One-To-One

▼魔方 西西 提交于 2019-12-06 14:12:35

问题


I need to set up a relationship that is currently a one-to-many:

public class Foo
{
    public int FooId { get; set; }
    public int? BarId { get; set; }
    ...
    public virtual Bar Bar { get; set; }
}

public class Bar
{
    public int BarId { get; set; }
    ...
    public virtual ICollection<Foo> Foos { get; set; }
}

public FooMap()
{
    HasKey(e => e.FooId);
    Property(e => e.FooId.IsRequired().HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
    Property(e => e.BarId).IsOptional();
    ...
    HasOptional(e => e.Bar).WithMany(Foos).HasForeignKey(e => e.BarId);
}

public BarMap()
{
    HasKey(e => e.BarId);
    Property(e => e.BarId.IsRequired().HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
    ...
    HasMany(e => e.Foos).WithOptional(e => e.Bar).HasForeignKey(e => e.BarId);
}

However, in reality, Bar can only be assigned to a single Foo. Is it possible to set this up so I have a single Foo navigation property in Bar rather than a collection of Foos? I still want my tables to render:

Foos
- FooId
- BarId (null)
- ...

Bars
- BarId
- ...

and I want my classes to be:

Foo
- FooId
- BarId
- ...
- Bar

Bar
- BarId
- ...
- Foo

I've been fiddling around with WithOptionalDependant and WithOptionalPrincipal, but can't find the correct combination. Any help is appreciated!


回答1:


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.



来源:https://stackoverflow.com/questions/15791961/entity-framework-fluent-mapping-optional-one-to-one

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