有没有更好的方法首先使用Entity Framework 7.0代码来处理这个数据库树结构

问题描述 投票:0回答:1

我正在使用 c# 和 Entity Framework 7.0 Code First 开发一个数据库。我遇到过一个对我来说有点棘手的场景。考虑以下实体图。

  • 一家商店有很多 Pod
  • 一家商店有很多职位
  • 一个Pod有多个Position

图表变成树形结构。这会对 Positions 表中的外键冗余产生不利影响。这也让导航类变得尴尬。我的职位课程看起来像这样

public class Position
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public string Name { get; set; }

    [ForeignKey(nameof(StoreId))] 
    public virtual Store Store { get; set; }
    public int StoreId { get; set; }

    [ForeignKey(nameof(PodId))]
    public virtual Pod Pod { get; set; }
    public int? PodId { get; set; }
}

上述场景在现实世界中存在得相当愉快。一个 Store 确实包含许多 Pod 和/或许多 Position。一个 Pod 还可以包含多个 Position。我只是想知道你们中一些更有经验的人可能会如何处理这个问题?

entity-framework asp.net-core ef-code-first
1个回答
0
投票

以下实体适用于您的关系。无需显式配置外键或其他模型构建器设置。

    public class Store
    {
        [Key]
        public int Id { get; set; }
        public string Name { get; set; }
        public IEnumerable<Pod> Pods { get; set; }
        public IEnumerable<Position> Positions { get; set; }
    }

    public class Pod
    {
        [Key]
        public int Id { get; set; }
        public string Name { get; set; }
        public IEnumerable<Position> Positions { get; set; }
    }
    public class Position
    {
        [Key]
        public int Id { get; set; }
        public string Name { get; set; }
    }
© www.soinside.com 2019 - 2024. All rights reserved.