Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to pass multiple Expressions to OrderBy for EF?
    text
    copied!<p>I am using EF 4.2, but I expect this would apply to EF 4 and 4.1 as well.</p> <p>I would like to pass an <code>IQueryable&lt;T&gt;</code> and multiple <code>Expression&lt;Func&lt;TSource, TKey&gt;&gt;</code> to a method and have the method apply <code>OrderBy</code> and <code>ThenBy</code> to the <code>IQueryable&lt;T&gt;</code> as appropriate.</p> <p>I found <a href="https://stackoverflow.com/questions/5047561/how-to-pass-an-array-of-orderby-expression-to-a-method/5235197#5235197">this answer</a>, and wrote the method below based on that:</p> <pre><code>public IQueryable&lt;User&gt; ApplyOrderBy(IQueryable&lt;User&gt; query, IEnumerable&lt;Expression&lt;Func&lt;User, IComparable&gt;&gt;&gt; orderBy) { if (orderBy == null) { return query; } IOrderedQueryable&lt;User&gt; output = null; foreach(var expression in orderBy) { if (output == null) { output = query.OrderBy(expression); } else { output = output.ThenBy(expression); } } return output ?? query; } </code></pre> <p>This works fine as long as the properties I order by are <code>string</code>s, but when I try to order by an <code>int</code> property, I get an exception:</p> <blockquote> <p>Unable to cast the type 'System.Int32' to type 'System.IComparable'. LINQ to Entities only supports casting Entity Data Model primitive types.</p> </blockquote> <p>Any suggestions to work around this, or for a different approach altogether? I considered passing in an <code>IEnumerable&lt;Expression&gt;</code>, but then would need to figure out how to cast back to the specific type (e.g. <code>Expression&lt;Func&lt;User, int&gt;</code>) to call <code>OrderBy</code>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload