0

I have this query :

dbContext.OrganizationHierarchyItems
         .Include(x => x.Parent)
         .Include(x => x.SubOrganizationHierarchyItems)
         .Where(x => x.Parent==null)
         .ToList();

And I need to flat all OrganizationHierarchyItems for root elements(Parent=null).

How can I flat self-reference entities using Entity Framework?

Update:

For now I came up with this code :

var organizationHierarchyItems=dbContext.OrganizationHierarchyItems.ToList();

var flattenHierarchyList = FlattenOrganizationGraph(organizationHierarchyItems.FirstOrDefault(x => x.Id==id), organizationHierarchyItems);

private IList<OrganizationHierarchyItem> FlattenOrganizationGraph(OrganizationHierarchyItem passedItem, List<OrganizationHierarchyItem> organizationHierarchyItems, IList<OrganizationHierarchyItem> result=null)
            {
                if (result == null)
                    result = new List<OrganizationHierarchyItem>();

                result.Add(passedItem);

                foreach (var item in organizationHierarchyItems.Where(x => x.ParentId==passedItem.Id).ToList())
                {
                    return FlattenOrganizationGraph(item, organizationHierarchyItems, result);
                }
                return result;

            }

But the problem with the code above is I am loading all OrganizationHierarchyItems to flatten only one root element's hierarchy.

Simple Code
  • 2,354
  • 2
  • 27
  • 56
  • If your question is: does EF have some magic function to do this for you, the answer is: no. In general: recursion with LINQ is something you have to do yourself. – Gert Arnold Jan 19 '18 at 12:23
  • By flat you mean just a list of the root elements without any childern? Just remove your includes and you should be fine. Or use Select(...) and project your root elements into new objects without parents and children. – Rob Jan 19 '18 at 12:23
  • @Robert by flat I meant all items underneath the root element until leaf items to get them in one level – Simple Code Jan 19 '18 at 12:25
  • In this particular case, all you need is to remove `Include`s and `Where` and just take the whole table - `dbContext.OrganizationHierarchyItems.ToList()`. It's already flat, and links are populated by EF navigation property fixup. – Ivan Stoev Jan 19 '18 at 13:46

0 Answers0