我有多个实体,我想共享一个“图像”表。例如,产品可以有图像列表,类别可以有图像列表。我想使用枚举“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);
Smart猫小萌
相关分类