Q:

How to build a hierarchical tree using EF and LINQ

I have the following code with which I'm trying to build a hierarchical / parent child relationship model using EF:
ICollection<Content> contentList = _dbset.Where(
                content =>
                content.CompanyId == companyId && content.ParentContentId == null && content.Deleted == false)
                .OrderBy(content => content.SortLevel)
                .Include(content => content.SubContent.Select(childContent => childContent.SubContent)).ToList();

How can I build a parent-child tree using EF in this scenario?

A:

Since EF tracks all objects loaded to the db context unless tracking is turned off on the actual query you can load all records you need to build the tree to the context and then write a linq query on the previous result set/collection to filter all the child->grandchild records by specify the parent id on the query. E.g
ICollection<object> treeList = <dbcontent>.<entity>.All().ToList();
treeList = treeList.Where(o => o.ParentId == 0).ToList();

