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!