吴五万
robs

导航

 
public static class LinqHelper
    {
        //NHibernate.Hql.Ast.HqlBooleanExpression
        public static Expression<Func<T, bool>> True<T>()
        {
            return f => true;
        }

        public static Expression<Func<T, bool>> False<T>()
        {
            return f => false;
        }

        public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expr1,
            Expression<Func<T, bool>> expr2)
        {
            InvocationExpression invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
            return Expression.Lambda<Func<T, bool>>
                (Expression.AndAlso(expr1.Body, invokedExpr), expr1.Parameters);
        }

        /// <summary>
        ///     排序
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="source"></param>
        /// <param name="propertyStr"></param>
        /// <param name="order"></param>
        /// <returns></returns>
        public static IQueryable<TEntity> OrderBy<TEntity>(this IQueryable<TEntity> source, string propertyStr, string order)
            where TEntity : class
        {
            ParameterExpression param = Expression.Parameter(typeof (TEntity));
            PropertyInfo property = typeof (TEntity).GetProperty(propertyStr);
            Expression propertyAccessExpression = Expression.MakeMemberAccess(param, property);
            LambdaExpression le = Expression.Lambda(propertyAccessExpression, param);
            Type type = typeof (TEntity);
            MethodCallExpression resultExp = Expression.Call(typeof (Queryable),
                order == "desc" ? "OrderByDescending" : "OrderBy",
                new[] {type, property.PropertyType}, source.Expression, Expression.Quote(le));
            return source.Provider.CreateQuery<TEntity>(resultExp);
        } 

    }

  

调用:
 var member = LinqHelper.True<Memberuser>();  //申请表达式
 

最后加入 where 条件语句
 var query = db.Members.Where(member).ToList();  //加入表达式

  

posted on 2019-06-27 16:14  吴五万  阅读(379)  评论(0编辑  收藏  举报