EF Core 5 多对多关系相同 table?
EF Core 5 many to many relationship to the same table?
一个产品可以有很多其他相关产品。以下内容完美地创建了联接 table,但是当我将产品添加到另一个产品的 RelatedProducts 时,保存时出现以下错误:'尝试保存更改时 'ProductAssociation.ProductID' 的值未知。这是因为 属性 也是关系中的主要实体未知的外键的一部分。
</p>
<pre>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 many-to-many relationships same table
我也在核心 3+ 中用上面提供的 link 解决了这个问题。
产品 table
public class Product
{
// Other properties members ....
public ICollection<Product> Products { get; set; }
public ICollection<Product> ProductOf { get; set; }
}
产品协会 table“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));
一个产品可以有很多其他相关产品。以下内容完美地创建了联接 table,但是当我将产品添加到另一个产品的 RelatedProducts 时,保存时出现以下错误:'尝试保存更改时 'ProductAssociation.ProductID' 的值未知。这是因为 属性 也是关系中的主要实体未知的外键的一部分。
</p>
<pre>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 many-to-many relationships same table
我也在核心 3+ 中用上面提供的 link 解决了这个问题。
产品 table
public class Product
{
// Other properties members ....
public ICollection<Product> Products { get; set; }
public ICollection<Product> ProductOf { get; set; }
}
产品协会 table“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));