当前在封装类EF的Where条件的表达式的解析逻辑,遇到的问题是:运用过程中可能需要将复杂的条件在不同的处理逻辑中Expression表达式进行拼接。
针对于遇到的问题写了示例进行记录,主要为了能够将Lambda表达式转为可执行的SQL语句,例子如下:
(相关的Lambda表达式转为SQL语句的整理待有空的时候再整理,这边先记录一下表达式的拼接)
// f or f2 or f3 Expression<Func<SimplifyClass, bool>> f = SC => SC.id > 0 && string.IsNullOrEmpty(SC.name); Expression<Func<SimplifyClass, bool>> f2 = SC => SC.sourcename != "AA" && SC.text == "CC"; Expression<Func<SimplifyClass, bool>> f3 = SC => SC.sourcename.Contains("D"); ParameterExpression pp = Expression.Parameter(typeof(SimplifyClass), "SC"); MemberExpression fleftL = Expression.Property(pp, typeof(SimplifyClass).GetProperty("id")); ConstantExpression fleftR = Expression.Constant(0); BinaryExpression where1 = Expression.LessThan(fleftR, fleftL); MemberExpression frightR = Expression.Property(pp, typeof(SimplifyClass).GetProperty("name")); MethodCallExpression where2 = Expression.Call(typeof(string).GetMethod("IsNullOrEmpty"), frightR); where1 = Expression.And(where1, where2); MemberExpression f2leftL = Expression.Property(pp, typeof(SimplifyClass).GetProperty("sourcename")); ConstantExpression f2leftR = Expression.Constant("AA"); BinaryExpression where3 = Expression.NotEqual(f2leftL, f2leftR); MemberExpression f2rightL = Expression.Property(pp, typeof(SimplifyClass).GetProperty("text")); ConstantExpression f2rightR = Expression.Constant("CC"); BinaryExpression where4 = Expression.Equal(f2leftL, f2rightR); where3 = Expression.And(where3, where4); where1 = Expression.Or(where1, where3); MemberExpression f3leftR = Expression.Property(pp, typeof(SimplifyClass).GetProperty("sourcename")); ConstantExpression f3rightR = Expression.Constant("D"); MethodCallExpression where5 = Expression.Call(f3leftR, typeof(string).GetMethod("Contains"), f3rightR); where1 = Expression.Or(where1, where5); Expression<Func<SimplifyClass, bool>> lambda = Expression.Lambda<Func<SimplifyClass, bool>>(where1, pp);
//lambda转为SQL语句为:((@P0 < [id]) AND (ISNULL([name],'')<>'')) OR (([sourcename] <> @P1) AND ([text] = @P2)) OR ([sourcename] LIKE '%D%')