title: IQueryable<T>.OrderBy<T, object> throws: Unable to cast the type 'System.Int16' to type 'System.Object'
body: <p>We are using a GenericCriteria class that is used to query an IQueryable without having direct access to it. Basically the query is built in the 'business' layer and passed on to the 'data access' layer. To prevent duplication it needs to be as generic as possible.</p>
  
  <p>Here's a simplified version of the GenericCriteria class:</p>
  
  <pre><code>public class GenericCriteria&lt;T&gt;
  {
      public Expression&lt;Func&lt;T, bool&gt;&gt; Where { get; set; }
      public Expression&lt;Func&lt;T, object&gt;&gt; OrderBy { get; set; }
  }
  </code></pre>
  
  <p>Resolving the criteria is done by an extension method on IQueryable:</p>
  
  <pre><code>public static IQueryable&lt;T&gt; ResolveCriteria&lt;T&gt;(this IQueryable&lt;T&gt; query, GenericCriteria&lt;T&gt; criteria)
  {
      query = query.Where(criteria.Where);
      query = query.OrderBy(criteria.OrderBy);
      return query;
  }
  </code></pre>
  
  <p>This is how its resolved in the data layer:</p>
  
  <pre><code>public ICollection&lt;Person&gt; GetPersons(GenericCriteria&lt;Person&gt; criteria)
  {
      using (var context = new EFContext())
      {
          return context.Persons
              .AsQueryable()
              .ResolveCriteria(criteria)
              .ToList();
      }
  }
  </code></pre>
  
  <p>An example of its usage:</p>
  
  <pre><code>var criteria = new GenericCriteria&lt;Person&gt;();
  criteria.Where = c =&gt; c.Age &gt; 20;
  criteria.OrderBy = c =&gt; c.Age;
  
  var persons = Data.Instance.GetPersons(criteria);
  </code></pre>
  
  <p>The problem is that Entity Framework is unable to handle the <em>object</em> type of the OrderBy expression, throwing an exception:</p>
  
  <pre><code>Unable to cast the type 'System.Int16' to type 'System.Object'
  </code></pre>
  
  <p>So what I am now trying to figure out is how I can make the GenericCriteria class accept some kind of generic OrderBy construction so EF will be able to do its thing.</p>
  
  <p>What should I be looking for?</p>
  
  <p>Update:</p>
  
  <p>In case it wasn't clear, I would rather avoid:</p>
  
  <pre><code>public class GenericCriteria&lt;T, TKey&gt;
  {
      public Expression&lt;Func&lt;T, bool&gt;&gt; Where { get; set; }
      public Expression&lt;Func&lt;T, TKey&gt;&gt; OrderBy { get; set; }
  }
  </code></pre>
  
  <p>Because the user of the class might not always want to order, so requiring a type seems a bit dirty.</p>