Entity Framework Fluent Mapping Optional One-To-On

2019-04-16 08:00发布

问题:

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.