簡體   English   中英

當一個實體具有復合主鍵時,Entity Framework Core 中的多對多關系

[英]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的情況下, CategoryValue是主鍵。

我在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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM