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