我有多個實體,我想共享一個“圖像”表。例如,產品可以有圖像列表,類別可以有圖像列表。我想使用枚舉“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 關注
- 133 瀏覽
添加回答
舉報
0/150
提交
取消