public AccountDto BuildHierarchyTreeRecursive(AccountHierarchy rootNode) { var dtos = _dbContext.AccountHierarchies .OrderBy(a => a.LevelPath.Length).ThenBy(a => a.LevelPath) .Where(a => a.LevelPath.StartsWith(rootNode.LevelPath)) //.Take(10000) // temp for testing .Select(AccountDto.MapToFromHierarchyEntity).ToList(); System.Console.WriteLine($"Building for {rootNode.Name}, with {dtos.Count} entities"); var bottom = dtos.Last(); System.Console.WriteLine($"Bottom is {bottom.Id} with level {bottom.Level}, hierarchy depth {bottom.Depth}"); int counter = 0; Stopwatch sw = Stopwatch.StartNew(); var levels = bottom.Level.Split("/", StringSplitOptions.RemoveEmptyEntries); // System.Console.WriteLine(levels.Length); AccountDto root = AccountDto.MapToFromHierarchyEntity(rootNode); root.Nodes = SetChildNodesOnDepthRecursive(root.Depth + 1, bottom.Depth, root, dtos, ref counter); sw.Stop(); System.Console.WriteLine($"Hierarchy loop - Total iterations: {counter}. Took {sw.ElapsedMilliseconds} ms"); return(root); }