0

I am trying to get all parents for a given Category as efficient as possible. I have found some old threads suggesting to use cte and view in the database but preferably I would like to avoid creating these altogether. Is there anyway I can do this without having to do multiple round trips to the database getting every parent until parent is null? If possible I would like to do it using LINQ Dot Notation.

https://stackoverflow.com/a/11929928/3850405

https://code.msdn.microsoft.com/windowsdesktop/Recursive-or-hierarchical-bf43a96e

Model:

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

    public string Name { get; set; }

    public int? ParentId { get; set; }

    public virtual Category Parent { get; set; }

    public virtual ICollection<Category> Children { get; set; }
}
Ogglas
  • 62,132
  • 37
  • 328
  • 418
  • Why make ParentId an integer. Instead use : public Category Parent; – jdweng Sep 14 '17 at 14:52
  • Unfortunately nothing has changed in this area, so the linked posts still apply. – Ivan Stoev Sep 14 '17 at 17:04
  • @IvanStoev Ok thanks for info. I only have three-four levels maximum in my current project so I decided to do it in code anyway. If we can't take the performance hit I will redo it. https://stackoverflow.com/a/46227096/3850405 – Ogglas Sep 14 '17 at 19:52

0 Answers0