1

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?

  • 1
    A little birdie tells me that there are keys in these classes. Can you add those in so we can see a clearer pic? Thx – Julie Lerman Jun 26 '15 at 23:10
  • Yeah in EF6 you can only use the primary key property as a foreign key for a 1:1 relationship. This is because we don't support alternate keys. This will be supported in EF7 (which is currently pre-release). If you let EF introduce a FK property for you that is not part of your class (often called an "independent association") then it will work (which is the Foo_Id property you saw it introducing in the database). – Rowan Miller Jun 30 '15 at 18:02
  • Hi @RowanMiller, where can I download EF7? In the nuget.org we have only EF 6.1.3 – Alexandre TRINDADE Sep 06 '15 at 09:36

0 Answers0