# Create a hierarchical tree with ordering field with entiry framework core

This is my model:

public class CaseType {
public int CaseTypeID { get; set; }
public int? ParentID { get; set; }
public string CaseTypeText { get; set; }
public int? OrderBy { get; set; }
}


I'm trying to create a hierarchical tree structure from this model with the following values:

CaseTypeID  ParentID   CaseTypeText   OrderBy
1          Null       CT A         1
2          Null       CT B         2
3          Null       CT C         3
4             1       CT A 1       1
5             1       CT A 2       2
6             3       CT C 1       1
7             3       CT C 2       2


Which should output as:

CT A
CT A 1
CT A 2
CT B
CT C
CT C 1
CT C 2


This link helped me create T-SQL which nearly did the job. It just wouldn't let me use the OrderBy column. It used the order of the records in the table. I decided I'm probably best doing it with EF and LINQ anyway but hopefully that should let you see what I'm trying to achieve.

This is the Index method from my controller:

public async Task<IActionResult> Index() {
var TopLevelCaseTypes = await _context.CaseTypes.Where(ps => ps.ParentID.HasValue == false).OrderBy(x => x.OrderBy).ToListAsync();
List<CaseType> outputView =  new List<CaseType>();
foreach (CaseType IndividualTopLevelCaseType in TopLevelCaseTypes) {
var AllSubCaseTypes = await _context.CaseTypes.Where(ps => ps.ParentID == IndividualTopLevelCaseType.CaseTypeID).OrderBy(x => x.OrderBy).ToListAsync();
foreach (CaseType IndividualSubCaseTypes in AllSubCaseTypes) {

This achieves what I need it to but is inefficient as it gets the top level CaseTypes (where ParentID is null) then for each one, see if there are any subCaseTypes, adding each CaseType and subCaseType as it arrives to an outputView which is pushed to the View. Is there a better way of writing this in my controller making one DB call but letting me use the OrderBy field to pick the order?
• I can use the code that was autogenerated with the controller return View(await _context.CaseTypes.ToListAsync()); to retrieve the same results as using the method used in the example var hierarchy = _context.CaseTypes.Include(e => e.Children).ToList(); return View(hierarchy); and don't have to have public CaseType Parent { get; set; } public ICollection<CaseType> Children { get; set; } in the model. – Glyn Nov 3 '17 at 16:29