EF Fluent API map 0..1 to 0..1 relationship

Hi guys I have a question about EF Fluent API (Code First :P). In my model I have

public class TABLE_A
{
   public virtual long Id {get; set;}
   .... 
   public virtual TABLE_B MyTableBRef {get; set;}
}


public class TABLE_B
{
   public virtual long Id {get; set;}
   .... 
   public virtual TABLE_A MyTableARef {get; set;}
}

How am I supposed to map a 0..1 to 0..1 relationship?

In the database on TABLE_B I have a column (FK) that references the PK of TABLE_A.

Answers


It is not possible to have navigational properties on both sides if you are using a column other than the PK of TABLE_B.

public class TABLE_A
{
   public virtual long Id {get; set;}
}


public class TABLE_B
{
   public virtual long Id {get; set;}
   .... 
   public virutal TABLE_A MyTableARef {get; set;}
}

public class MyContext : DbContext
{
    public DbSet<TABLE_A> As { get; set; }
    public DbSet<TABLE_B> Bs { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<TABLE_B>()
           .HasRequired(b => b.MyTableARef)
           .WithMany()
           .Map(b => b.MapKey("FK_Column_name));
    }
}

If the PK of TABLE_B is also a FK to TABLE_A then you can use shared PK mapping with navigational properties on both sides.

Edit:

You can use Shared PK mapping as follows

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<TABLE_B>()
       .HasRequired(b => b.MyTableARef)
       .WithOptional(a => a.MyTableBRef);
}

The Id of TABLE_B is also an FK to TABLE_A.


Need Your Help