简体   繁体   中英

Entity Framework Core Composite Key In One To Many Mapping

So have an issue coming up with mapping where we have two classes

public class Customer
{
    public int Id;
    public CustomerAddress StatementAddress
    public bool AlwaysTrue => true;
    public string Code;
}

public class CustomerAddress
{
    public int Id;
    public bool ForStatement;
    public string _CustomerCode
}

We than have a mapping set up like this:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Customer>()
        .HasOne(s => s.StatementAddress)
        .WithMany()
        .HasPrincipalKey(x=> new {x._CustomerCode, x.ForStatement})
        .HasForeignKey(s => new { s.Code, s.AlwaysTrue});
}

This is however causing an issue, as it seems to be on the database looking for a column of StatementAddress_CustomerCode and StatementAddress_ForStatement within the Customer table, which clearly are not things that exist - why isnt it looking for the Code table and simply passing through True for the AlwaysTrue?

I would have thought the way its defining keys would just Use the Code and Alwaystrue value, but seems to be looking for two columns made up of a combination of the Property name, appended with the property name from the other class =/

I would suggest two things here:

  1. You can either manually define column names like this:

     public class Customer { public int Id; public CustomerAddress StatementAddress; [Column("StatementAddress_ForStatement")] public bool AlwaysTrue => true; [Column("StatementAddress_CustomerCode")] public string Code; } 
  2. You can specify the foreign key with the ForeignKeyAttribute like this:

     public class Customer { public int Id; public CustomerAddress StatementAddress; [ForeignKey("StatementAddress"), Column(Order = 1)] public bool AlwaysTrue => true; [ForeignKey("StatementAddress"), Column(Order = 0)] public string Code; } 

    Keep in mind that for this option you have to set the column order attribute to match the one that the foreign key in the CustomerAddress table has.

Hope this helps!

So, to close this out -

This is something not currently possible in EF Core (2.1) and remains to be seen if it will be added in future versions - as present it only supports mapping through a single property

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