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