Entity Framework Core Composite Key In One To Many Mapping

c# entity-framework-core

Question

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 =/

1
0
7/23/2018 12:32:58 PM

Accepted Answer

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

0
11/7/2018 4:58:44 PM

Popular Answer

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!



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