/// <summary> /// 数据分页的方法 /// </summary> /// <typeparam name="S"></typeparam> /// <param name="PageIndex">当前页码</param> /// <param name="PageSize">每页显示条数</param> /// <param name="condition">数据查询条件表达式</param> /// <param name="orderByExpression">排序的条件表达式</param> /// <param name="IsDESC">是否为倒序</param> /// <returns></returns> public PageData<T> FindAll<S>(int PageIndex, int PageSize, Expression<Func<T, bool>> condition, Expression<Func<T, S>> orderByExpression, bool IsDESC) { var query = IsDESC ? (Data.CreateObjectSet<T>()).Where(condition).OrderByDescending(orderByExpression) : (Data.CreateObjectSet<T>()).Where(condition).OrderBy(orderByExpression); 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; }
Expression<Func<V_COM_Userlist, object>> orderByExpression; ///排序 if (!String.IsNullOrEmpty(orderBydr.SelectedValue)) { switch (orderBydr.SelectedValue) { case "point": orderByExpression = k => k.point; break; case "Money": orderByExpression = k => k.Money; break; } }
_V_COM_UserlistFunction.FindAll(_User_Page1._PageIndex, _User_Page1._PageNumber, where, orderByExpression, true);
Expression<Func<V_COM_Userlist, object>> orderByExpression;
写是没问题的但是执行的时候就会报错
。LINQ to Entities 仅支持强制转换 Entity Data Model 基元类型。
Expression<Func<V_COM_Userlist, object>> orderByExpression;
是不是第二个模板参数不能是 object,必须是具体类型。
自己解决了····
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; }
不错,我也想到是要用Expression Tree来解决