lundi 29 juin 2015

build query by reflection and get a parametrized sql query

I have the following helper:

    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;
    }

this works perfectly but gives me queries like:

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

when I want :

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

I think I should use a ParameterExpression instead of the ConstantExpression but then I can't figure out how to value said ParameterExpression.





Aucun commentaire:

Enregistrer un commentaire