EF动态排序

  转载的代码,改天再研究

public PageData<T> FindAll(int PageIndex, int PageSize, Expression<Func<T, bool>> condition, String orderByExpression, bool IsDESC)
        {
            var property = typeof(T).GetProperty(orderByExpression);
            var parameter = Expression.Parameter(typeof(T), "p");
            var propertyAccess = Expression.MakeMemberAccess(parameter, property);
            var orderByExp = Expression.Lambda(propertyAccess, parameter);
            var query = (Data.CreateObjectSet<T>()).Where(condition);
            string methodName = IsDESC ? "OrderByDescending" : "OrderBy";
            MethodCallExpression resultExp = Expression.Call(typeof(Queryable), methodName, new Type[] { typeof(T), property.PropertyType }, query.Expression, Expression.Quote(orderByExp));
            query = query.Provider.CreateQuery<T>(resultExp);
            PageData<T> pageData = new PageData<T>();
            pageData.TotalCount = query.Count();
            pageData.DataList = query.Skip((PageIndex - 1) * PageSize).Take(PageSize).ToList();
            ObjectQuery<T> ss = query as ObjectQuery<T>;
            String sss = ss.ToTraceString();
            return pageData;

        }
posted @ 2016-12-07 16:55  虚若影  阅读(1161)  评论(0编辑  收藏  举报