MVC3, Entity Framework 4.1 Code First.
Work with 2 tables
Model:
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; }
Dynamic expression for sorting (just to avoid the case switch statement):
public virtual IQueryable< ProgramMaster > GetQueryableSort(string sortField="", string sortDirection="") { IQueryable<ProgramMaster> 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<ProgramMaster>)query.Provider.CreateQuery< ProgramMaster >(call); return returnquery; }
The page displays a grid with two columns. Program name and university name using webgrid. The sorting function for the "Program Name" column, however, failed if it was sorted by university name, because this property is in UniversityMaster, and Expression.PropertyOrField searches for this property in ProgramMaster. Here is the exception:
University.UniversityName 'is not a member of the type' App.Core.Model.ProgramMaster
My question is how I do this work for the navigation properties of my model class.
I hope I could explain the scenario. Any help is appreciated.
Amddh source share