我有多个实体,我想共享一个“图像”表。例如,产品可以有图像列表,类别可以有图像列表。我想使用枚举“EntityType”来区分它是什么类型的实体。我下面的解决方案不起作用,因为当我尝试插入带有 EntityId 的图像时出现外键错误,该图像可能存在于 Category 中但不存在于 Product 中。这是有道理的,因为下面的解决方案没有考虑“EntityType”。是否有关于如何实现此目标的建议?我知道我可以使用“ProductId”、“CategoryId”等代替“EntityId”,但我会有很多实体,所以我不想那样做。public class Product{ public int Id { get; set; } public List<Image> ProductImages { get; set; }}public class Category{ public int Id { get; set; } public List<Image> CategoryImages { get; set; }}public class Image{ public int EntityId { get; set; } public EntityType EntityType { get; set; } public string ImageUrl { get; set; } public Product Product { get; set; } public Category Category { get; set; }}modelBuilder.Entity<Product>().ToTable("Product");modelBuilder.Entity<Category>().ToTable("Category");modelBuilder.Entity<Image>().ToTable("Image");modelBuilder.Entity<Image>().HasOne(p => p.Product).WithMany(p => p.ProductImages).HasForeignKey(p => p.EntityId);modelBuilder.Entity<Image>().HasOne(p => p.Category).WithMany(p => p.CategoryImages).HasForeignKey(p => p.EntityId);
1 回答

Smart猫小萌
TA贡献1911条经验 获得超7个赞
您所描述的是多对多关系。为此,您需要一个实体来跟踪所述关系:
public class ProductImage
{
[ForeignKey(nameof(Product))]
public int ProductId { get; set; }
public Product Product { get; set; }
[ForeignKey(nameof(Image))]
public int ImageId { get; set; }
public Image Image { get; set; }
}
在你的Product/Category类:
public ICollection<ProductImage> ProductImages { get; set; }
然后,对于您的流畅配置:
modelBuilder.Entity<ProductImage>().HasOne(p => p.Product).WithMany(p => p.ProductImages);
modelBuilder.Entity<ProductImage>().HasOne(p => p.Image).WithMany();
对您的类别执行相同的操作。
- 1 回答
- 0 关注
- 145 浏览
添加回答
举报
0/150
提交
取消