![](/img/trans.png)
[英]Using 2 databases sharing one model in Entity Framework Core
[英]Sharing a table using Entity Framework Core
我有多個實體,我想分享一個“圖像”表。 例如,產品可以具有圖像列表,並且類別可以具有圖像列表。 我想使用枚舉“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();
對您的類別執行相同操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.