Search code examples
c#entity-frameworkentity-relationshipfluent

zero to one with only one foreign key fluent mapping


I have two classes

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

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

I'm using fluent mapping with Entity Framework. How can I map the Foo and Bar together so that I can have :

One bar and one or zero foo

One foo and one or zero bar

I think this is a correct schema for the 3rd normal form. I know how to do it if Foo had a BarId foreign key, but it is not the case.


Solution

  • To do what you are asking you will need to configure two different unidirectional relationships:

    modelBuilder.Entity<Foo>()
                .HasOptional(s => s.Bar)
                .WithMany();
    
    modelBuilder.Entity<Bar>()
                .HasOptional(s => s.Foo)
                .WithMany()
                .HasForeignKey(s => s.FooId);