title: Ordering By Child Entity EF Core
body: <p>I have an extension method to sort my entities, and in some cases i need to sort on a property of a child collection</p>
  
  <pre><code> public static IQueryable&lt;Payment&gt; SetSort(this IQueryable&lt;Payment&gt; payments, string sortProperty, string direction)
  
  
              if (string.Equals(sortProperty, PaymentSortProperties.TimeStamp, StringComparison.CurrentCultureIgnoreCase))
              {
                  return sortDirection == SortDirection.Asc ? payments.OrderBy(x =&gt; x.History.OrderBy(h=&gt; h.Timestamp)) : payments.OrderByDescending(x =&gt; x.History.OrderByDescending(h =&gt; h.Timestamp));
              }
  
  }
  </code></pre>
  
  <p>Called from </p>
  
  <pre><code> public async Task&lt;IPagedList&lt;Payment&gt;&gt; Get(int pageNumber, int pageSize, string sortProperty, string direction, string searchString)
      {
              var result = _data.Payments
                  .Include(x =&gt; x.History)
                  .ThenInclude(x=&gt;x.Status)
                  .Filter(searchString)
              .SetSort(sortProperty, direction);
  
              return await result.ToPagedListAsync(pageNumber, pageSize);         
      }
  </code></pre>
  
  <p>i get the error <code>System.ArgumentException: At least one object must implement IComparable.</code></p>
  
  <p>I've seen examples that suggest i do it like this</p>
  
  <pre><code>    if (string.Equals(sortProperty, PaymentSortProperties.TimeStamp, StringComparison.CurrentCultureIgnoreCase))
                  {
                      return sortDirection == SortDirection.Asc ?
   payments.OrderBy(x =&gt; x.History.Min(h=&gt; h.Timestamp)) 
  : payments.OrderByDescending(x =&gt; x.History.Max(h =&gt; h.Timestamp));
                  }
  </code></pre>
  
  <p>but that triggers a <code>SELECT n + 1</code> query (ie causing all entities in dB to be loaded into memory, and then sorted).</p>
  
  <p>What is the right way of going about it?</p>