Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Apr 26th, 2012  |  syntax: None  |  size: 1.50 KB  |  hits: 17  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Dynamic LINQ Expression for sorting navigation property
  2. public class UniversityMaster
  3.     {
  4.         [Key]
  5.         public string UniversityId { get; set; }
  6.         public string UniversityName { get; set; }
  7.  
  8.     }
  9.  
  10.     public class ProgramMaster
  11.     {
  12.         [Key]
  13.         public string ProgramId { get; set; }
  14.         public string ProgramName { get; set; }
  15.         public string UniversityId { get; set; }
  16.  
  17.         public virtual UniversityMaster University { get; set; } // navigation property
  18.  
  19.     }
  20.        
  21. public virtual IQueryable< ProgramMaster > GetQueryableSort(string sortField="", string sortDirection="")
  22.         {
  23.             IQueryable<ProgramMaster> query = _dbSet;
  24.  
  25.             ParameterExpression pe = Expression.Parameter(typeof(ProgramMaster), string.Empty);
  26.             MemberExpression property = Expression.PropertyOrField(pe, sortField); //get a exception here if the sort field is of navigation property (University.UniversityName)
  27.  
  28.             LambdaExpression lambda = Expression.Lambda(property, pe);
  29.  
  30.  
  31.  
  32.             if (sortDirection == "ASC")
  33.                 orderbydir = "OrderBy";
  34.             else
  35.                 orderbydir = "OrderByDescending";
  36.  
  37.             MethodCallExpression call = Expression.Call(typeof(Queryable),
  38.                     orderbydir, new Type[] { typeof(TEntity), property.Type }, query.Expression, Expression.Quote(lambda));
  39.  
  40.             var returnquery = (IOrderedQueryable<ProgramMaster>)query.Provider.CreateQuery< ProgramMaster >(call);
  41.  
  42.             return returnquery;
  43.         }