[英]Many-to-many relationship in Entity Framework Core when one entity has composite primary key
我有以下課程:
public class InvoiceLine
{
public Guid Id { get; set; }
public int LineNumber { get; set; }
public List<ProductCode> ProductCodes { get; set; }
}
public class ProductCode
{
public string Category { get; set; }
public string Value { get; set; }
}
在ProductCode
的情況下, Category
和Value
是主鍵。
我在DbContext
中進行了DbContext
:
modelBuilder.Entity<ProductCode>()
.HasKey(pc => new { pc.Category, pc.Value });
一個InvoiceLine
可以有多個產品代碼,但一個產品代碼可以用於各種InvoiceLine
。
在 EF Core 中,我必須使用 ID 和實體創建一個連接實體:
public class InvoiceLineProductCode
{
public Guid InvoiceLineId { get; set; }
public InvoiceLine InvoiceLine { get; set; }
public ProductCode ProductCode { get; set; }
}
如何設置ProductCodeId
?
添加復合 FK 類似於添加單列 FK。
首先添加引用實體的 PK 列:
public class InvoiceLineProductCode
{
public Guid InvoiceLineId { get; set; }
public InvoiceLine InvoiceLine { get; set; }
public string ProductCodeCategory { get; set; } // <--
public string ProductCodeValue { get; set; } // <--
public ProductCode ProductCode { get; set; }
}
然后像往常一樣定義復合連接實體PK:
modelBuilder.Entity<InvoiceLineProductCode>()
.HasKey(e => new { e.InvoiceLineId, e.ProductCodeCategory, e.ProductCodeValue });
另外不要忘記更改Invoice
集合導航屬性類型:
public class InvoiceLine
{
public Guid Id { get; set; }
public int LineNumber { get; set; }
public List<InvoiceLineProductCode> ProductCodes { get; set; } // <--
}
並且由於名稱與 EF Core 約定匹配,因此您已完成。 如果他們不這樣做,關系ProductCode
-> InvoiceLineProductCode
的完整配置將是這樣的:
modelBuilder.Entity<InvoiceLineProductCode>()
.HasOne(e => e.ProductCode)
.WithMany()
.HasForeignKey(e => new { e.ProductCodeCategory, e.ProductCodeValue })
.IsRequired()
.OnDelete(DeleteBehavior.Cascade);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.