使用 Entity Framework Core 共享表

我有多个实体,我想共享一个“图像”表。例如,产品可以有图像列表,类别可以有图像列表。我想使用枚举“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);


蝴蝶刀刀
浏览 147回答 1
1回答

Smart猫小萌

您所描述的是多对多关系。为此,您需要一个实体来跟踪所述关系:public class ProductImage{&nbsp; &nbsp; [ForeignKey(nameof(Product))]&nbsp; &nbsp; public int ProductId { get; set; }&nbsp; &nbsp; public Product Product { get; set; }&nbsp; &nbsp; [ForeignKey(nameof(Image))]&nbsp; &nbsp; public int ImageId { get; set; }&nbsp; &nbsp; 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();对您的类别执行相同的操作。
打开App,查看更多内容
随时随地看视频慕课网APP