【问题标题】:Sharing a table using Entity Framework Core使用 Entity Framework Core 共享表
【发布时间】: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


【解决方案1】:

您所描述的是多对多关系。为此,您需要一个实体来跟踪所述关系:

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();

对您的类别做同样的事情。

【讨论】:

  • 我不确定我是否正在尝试进行多对多操作。我只想要一个引用图像表的产品。一张图片对应一款产品。然后我想要一个类别表来做同样的事情。我只是希望他们都共享同一个 Image 表。我不认为我需要一个连接表(如果我找到一种使用“EntityType”的方法)......但无论如何,我认为像你一样做多对多对我来说会更灵活建议..您的代码效果很好。谢谢!!
猜你喜欢
  • 2020-07-20
  • 1970-01-01
  • 2020-09-14
  • 2017-02-17
  • 1970-01-01
  • 2015-05-07
  • 1970-01-01
  • 2022-12-10
  • 1970-01-01
相关资源
最近更新 更多