【发布时间】:2019-04-11 15:27:36
【问题描述】:
我有多个实体想要共享一个“图像”表。例如,产品可以有一个图像列表,类别可以有一个图像列表。我想使用枚举“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);
【问题讨论】:
-
你发现了吗?我也在用文件附件实现类似的东西。
标签: c# asp.net-core entity-framework-core