Multiple One-to-One Relationships of the Same Type on Entity in Entity Framework

532 Views Asked by At

I have a model:

public class Foo
{
    public virtual Bar Bar1 { get; set; }
    public virtual Bar Bar2 { get; set; }
}

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

Bar1 and Bar2 are optional but Foo is required for all Bars. There is a Bar1_Id column and Bar2_Id column on the Foos table.

I tried this configuration:

modelBuilder
    .Entity<Foo>()
    .HasOptional(x => x.Bar1);

modelBuilder
    .Entity<Foo>()
    .HasOptional(x => x.Bar2);

modelBuilder
    .Entity<Bar>()
    .HasRequired(x => x.Foo);

Which generated a migration that tried to add a Foo_Id to the Bars table:

AddColumn("dbo.Bars", "Foo_Id", c => c.Guid(nullable: false));
CreateIndex("dbo.Bars", "Foo_Id");
AddForeignKey("dbo.Bars", "Foo_Id", "dbo.Foos", "Id", cascadeDelete: true);

Which isn't what I wanted, so I tried removing those lines from the migration and running the code which of course produced the error when trying to load a Bar:

Invalid column name 'Foo_Id'.

I then tried this configuration:

modelBuilder
    .Entity<Foo>()
    .HasOptional(x => x.Bar1)
    .WithRequired(x => x.Foo);

modelBuilder
    .Entity<Foo>()
    .HasOptional(x => x.Bar2)
    .WithRequired(x => x.Foo);

Which produced this error when migrating:

System.Data.Entity.Core.MetadataException: Schema specified is not valid. Errors: The relationship 'Test.Foo_Bar1' was not loaded because the type 'Test.Bars' is not available.

I have this sort of relationship elsewhere, but not where there are two of the same type on the entity. Is this a known limitation of EF6?

0

There are 0 best solutions below