【问题标题】:How do I define an entity class to be shared as a collection across multiple entities using Entity Framework Core?如何使用 Entity Framework Core 将实体类定义为跨多个实体共享的集合?
【发布时间】:2021-07-18 05:28:43
【问题描述】:

我在 ASP.NET Core Web API 中使用 Entity Framework Core 和 PostGreSQL。我很难定义一组 A 类和 B 类的实体 包含 C 类的集合。

在数据库迁移期间生成的结果表/列不是我所期望的。

考虑以下表格定义:

public class Supplier
{
    [Key]
    public Guid SupplierId { get; set; }
    public string SupplierName { get; set; }
    public List<Commodity> Commodities { get; set; }
}

public class Consumer
{
    [Key]
    public Guid ConsumerId { get; set; }
    public string ConsumerName { get; set; }
    public List<Commodity> Commodities { get; set; }
}

public class Commodity
{
    [Key]
    public Guid CommodityId { get; set; }
    public string CommodityName { get; set; }
}

这些类会生成以下表格/列:

Suppliers
   SupplierId
   SupplierName
   
Consumers
   ConsumerId
   ConsumerName
   
Commodities
   CommodityId
   CommodityName
   ConsumerId

如何创建模型类定义以便生成的表/列保留这些关系?有没有办法强制创建连接表?

我应该使用一组特定的类/字段注释吗?

【问题讨论】:

    标签: c# postgresql asp.net-core entity-framework-core


    【解决方案1】:
    public class Supplier
    {
        [Key]
        public Guid SupplierId { get; set; }
        public string SupplierName { get; set; }
        public ICollection<Commodity> Commodities { get; set; }
    }
    
    public class Consumer
    {
        [Key]
        public Guid ConsumerId { get; set; }
        public string ConsumerName { get; set; }
        public ICollection<Commodity> Commodities { get; set; }
    }
    
    public class Commodity
    {
        [Key]
        public Guid CommodityId { get; set; }
        public string CommodityName { get; set; }
       
        [Foreignkey("Supplier")
        public Guid SupplierId { get; set; }
        public Supplier Supplier { get; set; }
        
        
        [Foreignkey("Consumer")
        public Guid ConsumerId { get; set; }
        public Consumer Consumer{ get; set; }
    }
    

    为了更好地理解 ICollection 和 IList,我建议: ICollection vs List

    这个网页有一些关于与 EF 不同关系的好信息。 One-to-Many with EF

    根据默认约定,当一个属性的名称与相关实体的主键属性匹配时,EF 将其作为外键属性。 DataAnnotations

    【讨论】:

    • 感谢详细解释和链接。不知道 ICollection 与 List
    【解决方案2】:

    鉴于这些是一对多关系,我们希望 Commodity 表指向 Supplier 和 Consumer 表。您应该在 Commodity 模型中显式添加关系列:

    public class Commodity
    {
        [Key]
        public Guid CommodityId { get; set; }
        public string CommodityName { get; set; }
    
        public Guid SupplierId { get; set; }
        public Supplier Supplier { get; set; }
    
        public Guid ConsumerId { get; set; }
        public Consumer Consumer { get; set; }
    }
    

    无需更改供应商和消费者模型。此更改应将SupplierIdConsumerId 设置为外键,然后您应该能够从任一方访问关系。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-23
      • 2018-06-09
      • 2017-05-05
      • 1970-01-01
      • 2023-03-29
      • 1970-01-01
      • 1970-01-01
      • 2018-02-05
      相关资源
      最近更新 更多