简体   繁体   English

一对多映射中的实体框架核心组合键

[英]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? 但是,这引起了一个问题,因为它似乎是在数据库中寻找Customer表中的StatementAddress_CustomerCode和StatementAddress_ForStatement列,这些列显然不存在-为什么不查找Code表并简单地通过True来传递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 =/ 我本以为它的定义键只使用Code和Alwaystrue值的方式,但似乎正在寻找由属性名称的组合组成的两列,并附加了另一个类的属性名称= /

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: 您可以使用ForeignKeyAttribute指定外键,如下所示:

     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. 请记住,对于此选项,您必须设置列顺序属性以匹配CustomerAddress表中的外键所具有的属性。

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 这是EF Core(2.1)中目前无法实现的,是否会在将来的版本中添加还有待观察-目前,它仅支持通过单个属性进行映射

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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