天天看點

Expression.Constants 使用的小技巧

自己用表達式樹封裝了 Expression.And Expression.Or 用于多條件的表達式拼裝,在使用過程中,表達式中隻要用到Contains( Expression.Constants )就會報錯。報錯如下:

無法将類型為“NHibernate.Hql.Ast.HqlBitwiseAnd”的對象強制轉換為類型“NHibernate.Hql.Ast.HqlBooleanExpression”

剛開始還認為是Nhibernate不支援的問題,網上查了很多資料,最後參考了以下無博文,順利解決。

參考位址:https://www.cnblogs.com/hyl8218/archive/2013/03/12/2955074.html

解決方法如下:

在自己封裝的方法中, 使用Expression.AndAlso代替Expression.And即可。

public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2)
        {
            if (expr1 == null) return expr2;

            ParameterExpression newParameter = Expression.Parameter(typeof(T), "c");
            NewExpressionVisitor visitor = new NewExpressionVisitor(newParameter);

            var left = visitor.Replace(expr1.Body);
            var right = visitor.Replace(expr2.Body);
            //var body = Expression.And(left, right);
            var body = Expression.AndAlso(left, right);//解決Expression.Constant()報錯
            return Expression.Lambda<Func<T, bool>>(body, newParameter);

        }
           

繼續閱讀