title: Return Expression from a method to be used in OrderBy
body: <p>I want to write an abstract method to be overridden by child classes, and what the method does is return an expression to be subsequently used in LINQ <code>OrderBy()</code>. Something like this:</p>
  
  <p>Note: <code>Message</code> inherits from <code>Notes</code> class, and <code>MyModel</code> inherits from <code>MsgModel</code>.</p>
  
  <pre><code>public class Notes
  {
      // abstract definition; using object so that I can (I hope) order by int, string, etc.
      public abstract Expression&lt;Func&lt;MsgModel, object&gt;&gt; OrderByField();
      // ...
  
      private string GetOrderByFieldName()
      {
          // I am not sure how to write this
          // This is my problem 2. Please see below for problem 1 :-(
  
          var lambda = OrderByField() as LambdaExpression;
  
          MemberExpression member = lambda.Body as MemberExpression;
  
          PropertyInfo propInfo = member.Member as PropertyInfo;
  
          return propInfo.Name;
      }
  }
  
  public class Message : Notes
  {
      // second type parameter is object because I don't know the type
      // of the orderby field beforehand
      public override Expression&lt;Func&lt;MyModel, object&gt;&gt; OrderByField()
      {
          return m =&gt; m.item_no;
      }
  }
  </code></pre>
  
  <p>Now if I try to order by this way:</p>
  
  <pre><code>var orderedQuery = myQueryable.OrderBy(OrderByField());
  </code></pre>
  
  <p>I get this error:</p>
  
  <blockquote>
    <p>'Unable to cast the type 'System.Int32' to type 'System.Object'. LINQ to Entities only supports casting EDM primitive or enumeration types.'</p>
  </blockquote>
  
  <p>I can rightaway say that type parameter object is the cause of the problem. So, when I change the type parameter to int, it works fine as long as I am ordering by an int field (e.g. the field <code>item_no</code>).</p>
  
  <p>Q1. How can I get this to work? Surely, I can use a string property <code>OrderByField</code> instead of that expression-returning method and order by it, probably by writing some extension method for IQueryable (maybe using <a href="https://stackoverflow.com/questions/2841585/create-linq-to-entities-orderby-expression-on-the-fly">this great answer</a>). But I want to have more intellisense while setting the order by.</p>
  
  <p>Q2. How can I get the name of the order by column from the expression returned by the method <code>OrderByField()</code>. Obviously what I have tried with doesn't work. The <code>member</code> always gets null.</p>
  
  <hr>
  
  <p><strong>Edit:</strong> I have made some changes to the type parameters of the methods. Sorry for not doing it the first time.</p>