title: OrderBy in EF linq to entities can't handle the goodness I'm throwing at it.
body: <p>I am working on an app that uses Entity Framework 3.5 and an SQL database. The app searches an object graph based on some search criteria passed down from a user interface. In order to handle the search functionality, I'm using a query builder with the following interface:</p>
  
  <pre><code>public interface IQueryBuilder
  {
      IQueryable&lt;SomeClass&gt; BuildQuery(Criteria criteria);    
  }
  </code></pre>
  
  <p>The criteria object carries several properties that the query builder uses to filter the search results. It also carries a property that dictates how the results should be sorted, called "OrderBy". Here's an example of the criteria object:</p>
  
  <pre><code>public class Criteria
  {
      //some filter properties...
  
      public Expression&lt;Func&lt;SomeClass, object&gt;&gt; OrderBy { get; set; }
  }
  </code></pre>
  
  <p>So, after the initial query has been built, the query builder sorts the query with:</p>
  
  <pre><code>var sortedQuery = query.OrderBy(criteria.OrderBy);
  </code></pre>
  
  <p>This works flawlessly in unit tests and integration tests (where it actually hits EF) when I order by a string property (<code>OrderBy = x =&gt; something.LastName</code>). BUT, when I run integration tests that order by a non-string property (<code>OrderBy = x =&gt; something.AgeInYears</code>), EF throw the following exception:</p>
  
  <p><code>System.NotSupportedException: Unable to cast the type 'System.Int32' to type 'System.Object'. LINQ to Entities only supports casting Entity Data Model primitive types.</code></p>
  
  <p>In this case, <code>something.AgeInYears</code> is an <code>int</code>. EF doesn't like the fact that I give it an <code>int</code> instead of an <code>object</code>. </p>
  
  <p>SO, is there a way I can do what I'm trying to do here? </p>