This query will return a list of categories (and their included products, but the products are not relevant to this question). The categories with ParentId == null
will get sorted by SortOrder
, but the Children
categories will not. As I understand, this is not possible to acheive directly using LINQ, but can be done programmatically "post query".
How?
The query:
List<ProductCategory> DbCategories = _context.ProductCategories
.Include(e => e.Children)
.Include(e => e.ProductInCategory)
.ThenInclude(p => p.Product)
.ToList().OrderBy(o => o.SortOrder)
.Where(e => e.ParentId == null).ToList();
The result is displayed recursively in an unordered list, like so:
<ul>
<li>
Id=1,SortOrder=1,ParentId=null (sorted)
</li>
<li>
Id=2,SortOrder=2,ParentId=null (sorted)
</li>
<li>
Id=3,SortOrder=3,ParentId=null (sorted)
<ul>
<li>
Id=4,SortOrder=2,ParentId=3 (not sorted)
</li>
<li>
Id=5,SortOrder=3,ParentId=3 (not sorted)
</li>
<li>
Id=6,SortOrder=1,ParentId=3 (not sorted)
<ul>
<li>
<!-- ... and so on... nothing gets sorted further on either. -->
</li>
</ul>
</li>
</ul>
</li>
</ul>