通过反射构建查询并获取参数化的SQL查询

时间:2015-06-29 11:13:02

标签: linq reflection linq-to-entities

我有以下帮助:

    public static Expression<Func<TSource, Boolean>> BuildPredicate<TSource, TKey>(
        Expression<Func<TSource, TKey>> keySelector, String v, Boolean def = true) {

        if (!String.IsNullOrEmpty(v)) {
            if (v != "") {                    
                MethodInfo mi = typeof(String).GetMethod("Contains");
                MemberExpression expr = (MemberExpression)keySelector.Body;
                Expression e = null;
                foreach (String s in v.Split('|')) {
                    ConstantExpression cst = Expression.Constant(s.Trim());
                    MethodCallExpression mce = Expression.Call(expr, mi, cst);
                    if (e == null)
                        e = mce;
                    else
                        e = Expression.OrElse(e, mce);
                }

                return Expression.Lambda<Func<TSource, Boolean>>(e, keySelector.Parameters.First());
            }
        }

        return x => def;
    }

这完美无缺,但却给我提问:

... (col1 like '%value1%' or col1 like '%value2%' ... )

我想要的时候:

... (col1 like @p__linq__0 or col1 like @p__linq__1 ... )

我认为我应该使用ParameterExpression代替ConstantExpression,但我无法弄清楚如何评估所述ParameterExpression。

0 个答案:

没有答案