Skip to content

Sugar for HierarchyId path generation #32943

@Rezakazemi890

Description

@Rezakazemi890

I hope this message finds you well. I am writing to propose a feature enhancement for the HierarchyId type. I believe that the addition of a method or function for automatic path generation would greatly enhance the usability of the Hierarchy data structure.

To illustrate my suggestion, I have prepared a sample implementation using a TreeNode class:

public class TreeNode
{
    public TreeNode(int id, int? parentId, string name, HierarchyId path)
    {
        Id = id;
        ParentId = parentId;
        Name = name;
        Path = path;
    }

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

    public TreeNode? Parent { get; set; }
    public ICollection<TreeNode>? SubCategories { get; set; }
    public int? ParentId { get; set; }

    [Required]
    [StringLength(50)]
    public string Name { get; set; }

    public HierarchyId Path { get; set; }
}

Currently, when creating a new TreeNode, users are required to manually define the path with a specific format (Like "/1/1/2/"). For instance:

var root = new TreeNode(1, null, "Root", HierarchyId.GetRoot());
var first = new TreeNode(2, 1, "First", HierarchyId.Parse("/1/"));
var second = new TreeNode(3, 1, "Second", HierarchyId.Parse("/2/"));
var third = new TreeNode(4, 2, "Third", HierarchyId.Parse("/1/2/"));

This approach has the potential for error due to manual path formatting by users.

My suggestion is to introduce an automatic path generation method or function in the HierarchyId class, such as HierarchyId.GeneratePath(TreeNode parent) or a similar method for convenient and error-free path creation. This would streamline the process and reduce the likelihood of mistakes.

I believe that implementing this feature would contribute to a more robust and user-friendly experience when working with the HierarchyId type.

Thank you for considering my proposal.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions