title: Dynamic LINQ Expression for sorting navigation property
body: <p>MVC3, Entity Framework 4.1 Code first.</p>
  
  <p>Working with 2 tables</p>
  
  <p>Model:</p>
  
  <pre><code>public class UniversityMaster
  {
     [Key]
     public string UniversityId { get; set; }
     public string UniversityName { get; set; }
  
  }
  
  public class ProgramMaster
  {
      [Key]
      public string ProgramId { get; set; }
      public string ProgramName { get; set; }
      public string UniversityId { get; set; }
      public virtual UniversityMaster University { get; set; } // navigation property
  
  }
  </code></pre>
  
  <p>Dynamic expression for sorting (just to avoid a switch case statement):</p>
  
  <pre><code>public virtual IQueryable&lt; ProgramMaster &gt; GetQueryableSort(string sortField="", string sortDirection="")
     {
        IQueryable&lt;ProgramMaster&gt; query = _dbSet;
        ParameterExpression pe = Expression.Parameter(typeof(ProgramMaster), string.Empty);
        MemberExpression property = Expression.PropertyOrField(pe, sortField);
       //get a exception here if the sort field is of navigation property                            (University.UniversityName)
        LambdaExpression lambda = Expression.Lambda(property, pe);
        if (sortDirection == "ASC")
           orderbydir = "OrderBy";
        else
           orderbydir = "OrderByDescending";
           MethodCallExpression call = Expression.Call(typeof(Queryable),
           orderbydir, new Type[] { typeof(TEntity), property.Type }, query.Expression,  Expression.Quote(lambda));
  
        var returnquery = (IOrderedQueryable&lt;ProgramMaster&gt;)query.Provider.CreateQuery&lt; ProgramMaster &gt;(call);
        return returnquery;
      }
  </code></pre>
  
  <p>The page is displaying a grid with two columns Program Name and University Name using webgrid. The sorting work fine for Program Name column, however fails if sorted by University Name as this property is in UniversityMaster and the Expression.PropertyOrField searches this property in ProgramMaster. Here is the exception:</p>
  
  <blockquote>
    <p>University.UniversityName' is not a member of type 'App.Core.Model.ProgramMaster</p>
  </blockquote>
  
  <p>My question is how I make this work for navigation properties of my model class. </p>
  
  <p>Hope I was able explain the scenario. Any help is appreciated. </p>