一个产品可以有许多其他相关产品。以下内容完美地创建了联接表,但是当我将一个产品添加到另一个产品的相关产品时,我在保存时收到以下错误:“尝试保存更改时,‘ProductAssociation.ProductID’的值未知。”这是因为该属性也是外键的一部分,而关系中的主要实体是未知的。
modelBuilder.Entity<Product>()
.HasMany(x => x.RelatedProducts)
.WithMany(r => r.RelatedProducts)
.UsingEntity<ProductAssociation>(
x => x.HasOne(p => p.RelatedProduct).WithMany().HasForeignKey(f => f.RelatedProductID),
x => x.HasOne(p => p.Product).WithMany().HasForeignKey(f => f.ProductID).OnDelete(DeleteBehavior.NoAction),
x => x.ToTable("ProductAssociations"));
我认为这是一个类似的答案 Entity Framework Core 2.0 多对多关系同表
我还通过在核心 3+ 中提供上面的链接解决了这个问题。
产品表
public class Product
{
// Other properties members ....
public ICollection<Product> Products { get; set; }
public ICollection<Product> ProductOf { get; set; }
}
产品关联表“ProductSet”
public class ProductSet
{
public int ProductId { get; set; }
public int SubProductId { get; set; }
}
OnModelCreating()
modelBuilder.Entity<Product>()
.HasMany(e => e.Products)
.WithMany(e => e.ProductOf)
.UsingEntity<ProductSet>(
e => e.HasOne<Product>().WithMany().HasForeignKey(e => e.ProductId),
e => e.HasOne<Product>().WithMany().HasForeignKey(e => e.SubProductId));