title: Entity Framework 4: How to turn a string into an object for .OrderBy(p => p.fieldname)?
body: <p>Now this is a trick question because you <strong>cannot</strong> do this:</p>
  
  <pre><code>var a = myDB.Where(p =&gt; p.field == "filter").OrderBy("it." + fieldname);
  </code></pre>
  
  <p>You could change the Where to accept a string, which allows you to change the OrderBy to accept a string, but that's not the question.</p>
  
  <p><strong>How can you turn a string like "productID, productName" in to an OrderBy expression</strong>?  If I am correct in thinking, maybe the question could be "how to turn a Specification Pattern in to an Expression delegate?"</p>
  
  <p>The problem is I don't know what table they want, and thus I don't know the primary key. I used generics to represent the type of table.</p>
  
  <pre><code>public interface IRepository&lt;E, C&gt; where C : ObjectContext  // E is an Entity
  {
    void Add(E entity);
    void Del(E entity);
    IList&lt;E&gt; Get(Expression&lt;Func&lt;E, bool&gt;&gt; filterLambda = null,   //Where clause
                Expression&lt;Func&lt;E, object&gt;&gt; orderbyLambda = null, //OrderBy
                int? page = null,                                 //Page to get
                int? pageSize = null,                             //Page Size
                Expression&lt;Func&lt;E, object&gt;&gt; selectLambda = null); //Populate Fields
    int Count(Expression&lt;Func&lt;E, bool&gt;&gt; filterLambda = null);
    bool SaveChanges();
  }
  </code></pre>
  
  <p>The actual statement I use to pull content from the data context (data container?) is </p>
  
  <pre><code>this.GetEntity().Where(filterLambda)
                  .OrderBy(orderbyLambda)
                  .Skip(((int)page - 1) * (int)pageSize)
                  .Take((int)pageSize)
                  .Select(selectLambda).ToList();
  </code></pre>
  
  <p>I <strong>need</strong> the <code>OrderBy()</code> to implement <code>.Skip()</code> and <code>.Take()</code>.  For all those of you who think you can do this are correct for Linq to SQL.  However, Linq to Entities does not support it:</p>
  
  <pre><code>The method 'Skip' is only supported for sorted input in LINQ to Entities.
  The method 'OrderBy' must be called before the method 'Skip'.
  </code></pre>