亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 Entity Framework Core 共享表

使用 Entity Framework Core 共享表

C#
蝴蝶刀刀 2022-12-04 11:15:05
我有多個實體,我想共享一個“圖像”表。例如,產品可以有圖像列表,類別可以有圖像列表。我想使用枚舉“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();

對您的類別執行相同的操作。


查看完整回答
反對 回復 2022-12-04
  • 1 回答
  • 0 關注
  • 133 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號