Entity Framework Foreign Key Mapping

c# ef-fluent-api entity-framework entity-framework-6

Question

I'm trying to determine what EF6 is telling me, and it's not making much sense to me, so I'm hoping someone here can clarify this.

I'm setting up my FluentApi as so (composite keys in use in the DB, this is Code First from Database):

modelBuilder.Entity<Object1>()
    .HasKey(e => new { e.Property1, e.Property2 }
    .HasMany(e => e.Object2s)
    .WithRequired(e => e.Object1)
    .HasForeignKey(e => new { e.Property1, e.Property2 });

modelBuilder.Entity<Object2>()
    .HasKey(e => new { e.Property2, e.Property3, e.Property1 })
    .HasRequired(e => e.Object1)
    .WithMany(e => e.Object2s)
    .HasForeignKey(e => new { e.Property1, e.Property2 });

All builds fine, but when I go to select anything, I get this:

"Foreign key constraint 'Object1_Object2' from table Object2 (Property2, Property1) to table Object1 (Property1, Property2):: Insufficient mapping: Foreign key must be mapped to some AssociationSet or EntitySets participating in a foreign key association on the conceptual side."

Ideas? I don't understand why the FK constraint is showing Object2's FK in the incorrect order, when I've defined the correct order in the FluentApi.

1
1
5/29/2016 5:56:07 AM

Popular Answer

This is ultimately what I had to do - set the Foreign Key attribute, and specify Column order. The Code First from DB had Order=2 and Order=0 reversed, so I changed it to:

public partial class Object2
{
    [Key]
    [Column("Property2", Order=2)]
    [ForeignKey("Object1")]
    public short Property2 { get; set; }

    [Key]
    [Column("Property3", Order=1)]
    public short Property3 { get; set; }

    [Key]
    [Column("Property1", Order=0)]
    [ForeignKey("Object1")]
    public int Property1 { get; set; }
}

I removed the FluentApi from both Object1 and Object2 relating to this foreign key arrangement, and all appears well. I'll re-do it in FluentApi as soon as I determine how to set the column order in FluentApi.

Then I have to add this to my T4 file for this object... ultimate goal is to be able to regenerate the DB to Code First at any time without issue :) Thanks for the help, all!

0
5/29/2016 1:35:40 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow