简体   繁体   中英

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?

  1. List all location item at root (dept = 0)
  2. List all location hierarchy. for example..
  • location A
    • location B
    • location C
  • location D
    • location E
      • location J
    • location F
      • location K
      • location L
  • location M
  1. List all child location under the selected node and prefer dept level (ex 1, 2, or the rest).
  2. List all parent location under the selected node and prefer dept level (ex 1, 2, or the rest).

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.

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. 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 .

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(); your desired output will be obtained.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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