[英]Many-to-many relationship in Entity Framework Core when one entity has composite primary key
[英]Entity Framework Core Composite Key In One To Many Mapping
所以有一个关于映射的问题,我们有两个类
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
}
我们将像这样设置映射:
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});
}
但是,这引起了一个问题,因为它似乎是在数据库中寻找Customer表中的StatementAddress_CustomerCode和StatementAddress_ForStatement列,这些列显然不存在-为什么不查找Code表并简单地通过True来传递AlwaysTrue?
我本以为它的定义键只使用Code和Alwaystrue值的方式,但似乎正在寻找由属性名称的组合组成的两列,并附加了另一个类的属性名称= /
我在这里建议两件事:
您可以像这样手动定义列名称:
public class Customer { public int Id; public CustomerAddress StatementAddress; [Column("StatementAddress_ForStatement")] public bool AlwaysTrue => true; [Column("StatementAddress_CustomerCode")] public string Code; }
您可以使用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; }
请记住,对于此选项,您必须设置列顺序属性以匹配CustomerAddress
表中的外键所具有的属性。
希望这可以帮助!
所以,要结束这一点-
这是EF Core(2.1)中目前无法实现的,是否会在将来的版本中添加还有待观察-目前,它仅支持通过单个属性进行映射
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.