简体   繁体   中英

Entity Framework Foreign Key Mapping

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.

Try attribute :

//using System.ComponentModel.DataAnnotations.Schema

public class Object1
{

    public int Property1{ get; set; }
    public string Property2 { get; set; }

    //Foreign key for Object2
    public int FK_Object2_Property { get; set; }

    [ForeignKey("FK_Object2_Property")]
    public Object2 Object2 { get; set; }
}
public class Object2
{

    public int Property1{ get; set; }
    public string Property2 { get; set; }

    public ICollection<Object1> Objects { get; set; }
}

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM