0

How I can generate HierarchyId automatically/programmatically in .NET Core, I set a Category as another's child and expect the HierarchyId field to be updated automatically but nothing happens.

Do I need a method to calculate and update it manually?

public class Category : BaseModelSimple<int>
{
    public HierarchyId Node { get; set; }

    public int? ParentId { get; set; }

    [ForeignKey("ParentId")]
    public virtual Category Parent { get; set; }

    public virtual ICollection<Category> Childs { get; set; }
}
Mertez
  • 1,061
  • 3
  • 14
  • 38

1 Answers1

1

HierarchyId columns do not auto-generate values, and you can apparently even input duplicates unless you also have an index enforcing unique values, which might be problematic if you need multiple root entries. Most of the examples I've seen pre-populate the root node, and then add children from there, which involves getting the node you want to add a child to, getting all of the children, figuring out which is the last, and then adding on top of that.

You might find a review of the following link to be helpful in getting started, and hopefully you won't run into the same issue I have where I'm not able to add data via .NET because I keep getting a casting error.

Using HierarchyId with Entity Framework Core

Dharman
  • 30,962
  • 25
  • 85
  • 135