首页 > 解决方案 > 如何在 Entity Framework Core 中定义一个共享实体并使其他实体与它具有一对多的关系?

问题描述

我想定义一个共享实体,如下所示:

class Image
{
    public int ID { get; set; }
    public string  FileName { get; set; }
    public int Length { get; set; }
    public byte[] Data { get; set; }     // image binary data
    ...
}

因为,我有多个实体将与 Image 实体具有一对多的关系。

class Product
{
    public int ID { get; set; }
    public string  ProductName { get; set; }
    List<Image> ProductAvatars { get; set; }
    ...
}

class Category
{
    public int ID { get; set; }
    public string  CategoryName { get; set; }
    List<Image> CategoryAvatars { get; set; }
    ...
}

我认为图像实体不属于一个特定实体(例如产品或类别),因此定义外键Image没有意义。我应该添加更多如下关联表吗?

class ProductAvatars
{
    public int ProductID { get; set; }
    public int ImageID { get; set; }   // it's a foreign key of Image entity
}

class CategoryAvatars
{
    public int CategoryID { get; set; }
    public int ImageID { get; set; }    // it's a foreign key of Image entity
}

如何做到这一点?请给我一些建议,谢谢大家!

标签: c#asp.net-coreentity-framework-core

解决方案


选项1

您可以使用连接类型:

public class ProductImage {
    public Product Product { get; set; }
    public Image Image {get; set; }
}

public class CategoryImage {
    public Category Category { get; set; }
    public Image Image {get; set;
}

Product并且Category不会有List<Image>,但是List<ProductImage>List<CategoryImage>


选项 2

使用两个可为空的 FK 列,如下所示:

class Image
{

            public int ID { get; set; }
            public int? ProductId {get; set; } // by making the Id nullable, the FK is optional
            public Product Product { get; set;}
            public int? CategoryId { get; set;}
            public Category Category { get; set;}
            public string FileName { get; set; }
            public int Length { get; set; }
            public byte[] Data { get; set; }     // image binary data

}

推荐阅读