【问题标题】:Entity framework core closure table (Code First)实体框架核心闭表(代码优先)
【发布时间】:2019-07-22 00:07:52
【问题描述】:

我已经搜索了互联网以创建一个表来支持树数据或层次结构数据,但它似乎没有提供太多信息。

假设我想要一个 Location 表,如果有其他位置数据的父级,它可以自我引用。

如何在 ef-core 中实现如下查询?

  1. 列出根目录下的所有位置项 (dept = 0)
  2. 列出所有位置层次结构。例如..
  • 位置 A
    • 位置 B
    • 位置 C
  • 位置 D
    • 位置 E
      • 位置 J
    • 位置 F
      • 位置 K
      • 位置 L
  • 位置 M
  1. 列出所选节点下的所有子位置并首选部门级别(例如 1、2 或其他)。
  2. 列出所选节点下的所有父位置并首选部门级别(例如 1、2 或其他)。

这是我的位置模型...

public class Location
{
    public int Id { get; set; }

    [Required]
    public string Name { get; set; }

    public string Address { get; set; }

    public NpgsqlTsVector SearchVector { get; set; }
}

请帮助或提供任何建议的资源开始会很好。我是 dotnet 核心和实体框架的新手。

谢谢。

【问题讨论】:

    标签: c# .net-core ef-code-first entity-framework-core ef-core-2.2


    【解决方案1】:

    你想要的实体似乎是这样的:

    public class Location
    {
        public int Id { get; set; }
        [Required]
        public string Name { get; set; }
        public string Address { get; set; }
        public NpgsqlTsVector SearchVector { get; set; }
        public int? ParentId { get; set; }
        public Location Parent { get; set; }
    }
    

    ParentId? 是因为您的根没有任何父母。因此,根(或可能的根)是没有任何ParentId 的那个,树的其他部分也可以由它们的ParentIds 确定。

    更新:

    关于第二个问题,如果要读取层次结构的数据,还需要在实体中添加另一个属性:

    public virtual List<Location> Children { get; set; }
    

    具有以下配置:

    HasMany(c => c.Children).WithOptional(c => c.Parent).HasForeignKey(c => c.ParentId);
    

    因此,对于上述实体,只需执行 db.Location.toList();将获得您想要的输出。

    【讨论】:

    • aha,你能指导我在这个模型的基础上至少查询第 2 个问题(列出所有位置层次结构。)
    • 您能澄清更多吗?您所说的位置层次结构究竟是什么意思?输入和期望的输出是什么?
    • 嘿@rad 我有更新问题要显示和输出示例
    • 通过示例,您的意思是输入是单个位置,输出必须是它的所有子孙和...?
    • 只列出所有树而无需任何输入。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-05
    • 1970-01-01
    相关资源
    最近更新 更多