[英]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.