前言:在使用EF当中,肯定会遇到动态查询的需求,建立一个公共调用的动态组合表达式查询也是必不可少的,以下是建立动态组合多排序字段做个记录,供以后调用
1、建立一个结构,用于多个排序字段组合,这个结构体有两个字段,一个是需要排序的属性名,一个是是否是升序降序的判断
public struct OrderModelField { public string propertyName { get; set; } public bool IsDESC { get; set; } }
组合方法
public IList GetAllEntity(Expression<func<t, bool>> condition, int pageIndex, int pageSize, out long total, params OrderModelField[] orderByExpression) { //条件过滤 var query = this.QQYALIEntities.Set().Where(condition); //创建表达式变量参数 var parameter = Expression.Parameter(typeof(T), "o"); if (orderByExpression != null && orderByExpression.Length > 0) { for (int i = 0; i < orderByExpression.Length; i++) { //根据属性名获取属性 var property = typeof(T).GetProperty(orderByExpression[i].propertyName); //创建一个访问属性的表达式 var propertyAccess = Expression.MakeMemberAccess(parameter, property); var orderByExp = Expression.Lambda(propertyAccess, parameter); string OrderName = orderByExpression[i].IsDESC ? "OrderByDescending" : "OrderBy"; MethodCallExpression resultExp = Expression.Call(typeof(Queryable), OrderName, new Type[] { typeof(T), property.PropertyType }, query.Expression, Expression.Quote(orderByExp)); query = query.Provider.CreateQuery(resultExp); } } total = query.Count(); return query.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList(); }
原文:http://www.cnblogs.com/yannis/p/3584818.html