简体   繁体   English

实体框架核心关闭表(代码优先)

[英]Entity framework core closure table (Code First)

I have search out the internet to create a table to support tree data or hierarchy data but it seems not to provide much information. 我已经搜索了互联网以创建一个表来支持树数据或层次结构数据,但似乎并没有提供太多信息。

Let's say I want to have a Location table which can self-referencing if there is a parent by other location data. 假设我想要一个位置表,该表可以在其他位置数据存在父项的情况下自引用。

How can I achieve the following query in ef-core? 如何在ef-core中实现以下查询?

  1. List all location item at root (dept = 0) 列出根目录下的所有位置项目(部门= 0)
  2. List all location hierarchy. 列出所有位置层次结构。 for example.. 例如..
  • location A 位置A
    • location B 位置B
    • location C 位置C
  • location D 位置D
    • location E 位置E
      • location J 位置J
    • location F 位置F
      • location K 位置K
      • location L 位置L
  • location M 位置M
  1. List all child location under the selected node and prefer dept level (ex 1, 2, or the rest). 列出所选节点下的所有子位置,并优先选择部门级别(例如1、2或其他)。
  2. List all parent location under the selected node and prefer dept level (ex 1, 2, or the rest). 列出所选节点下的所有父级位置,并优先选择部门级别(例如1、2或其他)。

Here is my Location model... 这是我的位置模型...

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

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

    public string Address { get; set; }

    public NpgsqlTsVector SearchVector { get; set; }
}

Please help or give any suggest resource to start would be nice. 请帮助或提供任何建议资源开始将是不错的。 I'm new to dotnet core and entity framework. 我是dotnet核心和实体框架的新手。

Thank you. 谢谢。

You desired entity seems to be something like this: 您想要的实体似乎是这样的:

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; }
}

The ? ? for ParentId is because your root doesn't have any parents. 对于ParentId是因为您的根没有任何父母。 Therefore, the root (or possibly roots) is the one that does not have any ParentId and also other parts of the tree can be determined by their ParentIds . 因此,一个或多个根是不具有任何ParentId并且树的其他部分也可以由其ParentIds确定。

Update: 更新:

Regarding question number two, if you want to read the data with a hierarchy structure, another property is also required to be added to the entity: 关于第二个问题,如果要读取具有层次结构的数据,则还需要向该实体添加另一个属性:

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

with the following configuration: 具有以下配置:

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

Therefore, with the above entity, by simply executing db.Location.toList(); 因此,对于上述实体,只需执行db.Location.toList();。 your desired output will be obtained. 您将获得所需的输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM