我有多个实体,我想分享一个“图像”表。例如,产品可以具有图像列表,并且类别可以具有图像列表。我想使用枚举“EntityType”来区分它是什么类型的实体。我的解决方案不起作用,因为当我尝试插入具有可能存在于Category但不存在于Product中的EntityId的图像时,存在外键错误。这是有道理的,因为下面的解决方案没有考虑“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);
你所描述的是多对多的关系。为此,您需要一个实体来跟踪所述关系:
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();
对您的类别执行相同操作。