Entity framework core closure table (Code First)

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

Question

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.

1
0
2/28/2019 6:51:54 AM

Popular Answer

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.

0
2/28/2019 5:05:40 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow