动态LINQ喜欢

时间:2009-10-31 15:43:10

标签: linq dynamic

如何为Like子句编写动态LINQ方法。

供参考,有Dynamic LINQ OrderBy on IEnumerable<T> / IQueryable<T>。我正在为动态Like子句寻找类似的。

我有以下扩展方法:

public static IQueryable<T> Like<T>(this IQueryable<T> source, string propertyName, 
                                    string keyword)
{
    var type = typeof(T);
    var property = type.GetProperty(propertyName);
    var parameter = Expression.Parameter(type, "p");
    var propertyAccess = Expression.MakeMemberAccess(parameter, property);
    var constant = Expression.Constant("%" + keyword + "%");
    var methodExp = Expression.Call(
        null, 
        typeof(SqlMethods).GetMethod("Like", new[] { typeof(string), typeof(string) }),
        propertyAccess, 
        constant);
    var lambda = Expression.Lambda<Func<T, bool>>(methodExp, parameter);
    return source.Where(lambda);
}

上述方法给出错误

  

方法'Boolean Like(System.String,System.String)'不能在客户端上使用;它仅用于转换为SQL。

Dynamic LINQ OrderBy on IEnumerable<T> / IQueryable<T>以某种方式修改的另一种方法:

public static IQueryable<T> ALike<T>(this IQueryable<T> source, string property, 
                                     string keyword)
{
    string[] props = property.Split('.');
    Type type = typeof(T);
    ParameterExpression arg = Expression.Parameter(type, "x");
    Expression expr = arg;

    foreach (string prop in props)
    {
        // use reflection (not ComponentModel) to mirror LINQ
        PropertyInfo pi = type.GetProperty(prop);
        expr = Expression.Property(expr, pi);
        type = pi.PropertyType;
    }
    var constant = Expression.Constant("%" + keyword + "%");
    var methodExp = Expression.Call(
        null, 
        typeof(SqlMethods).GetMethod("Like", new[] { typeof(string), typeof(string) }), 
        expr, 
        constant);
    Type delegateType = typeof(Func<,>).MakeGenericType(typeof(T), type);
    LambdaExpression lambda = Expression.Lambda(delegateType, methodExp, arg);
    object result = typeof(Queryable).GetMethods().Single(
            method => method.IsGenericMethodDefinition
                    && method.GetGenericArguments().Length == 2
                    && method.GetParameters().Length == 2)
            .MakeGenericMethod(typeof(T), type)
            .Invoke(null, new object[] { source, lambda });
    return (IQueryable<T>)result;
}

上述方法出错:

  

类型'System.Boolean'的表达式不能用于返回类型'System.String'

有关于此的任何想法吗?

3 个答案:

答案 0 :(得分:6)

类似的东西:

static void Main() {
    using(var ctx= new DataClasses1DataContext()) {
        ctx.Log = Console.Out;
        var qry = ctx.Customers.WhereLike("CompanyName", "a%s");

        Console.WriteLine(qry.Count());
    }
}
static IQueryable<T> WhereLike<T>(this IQueryable<T> source,
        string propertyOrFieldName, string pattern) {
    var param = Expression.Parameter(typeof(T), "row");
    var body = Expression.Call(
        null,
        typeof(SqlMethods).GetMethod("Like",
            new[] { typeof(string), typeof(string) }),
        Expression.PropertyOrField(param, propertyOrFieldName),
        Expression.Constant(pattern, typeof(string)));
    var lambda = Expression.Lambda<Func<T, bool>>(body, param);
    return source.Where(lambda);
}
static IQueryable<T> WhereLike<T>(this IQueryable<T> source,
        string propertyOrFieldName, string pattern, char escapeCharacter) {
    var param = Expression.Parameter(typeof(T), "row");
    var body = Expression.Call(
        null,
        typeof(SqlMethods).GetMethod("Like",
            new[] { typeof(string), typeof(string), typeof(char) }),
        Expression.PropertyOrField(param, propertyOrFieldName),
        Expression.Constant(pattern, typeof(string)),
        Expression.Constant(escapeCharacter,typeof(char)));
    var lambda = Expression.Lambda<Func<T, bool>>(body, param);
    return source.Where(lambda);
}

您也可以考虑让它更具可重用性:

static void Main() {
    using(var ctx= new DataClasses1DataContext()) {
        ctx.Log = Console.Out;
        var qry1 = ctx.Customers.WhereInvoke<Customer, string>(
            "CompanyName", s => s.Contains("abc"));
        Console.WriteLine(qry1.Count());

        var qry2 = ctx.Customers.WhereInvoke<Customer, string>(
            "CompanyName", s => s.StartsWith("abc"));
        Console.WriteLine(qry2.Count());

        var qry3 = ctx.Customers.WhereInvoke<Customer, string>(
            "CompanyName", s => s.EndsWith("abc"));
        Console.WriteLine(qry3.Count());
    }
}
static IQueryable<TSource> WhereInvoke<TSource, TValue>(
        this IQueryable<TSource> source,
        string propertyOrFieldName,
        Expression<Func<TValue, bool>> func) {
    var param = Expression.Parameter(typeof(TSource), "row");
    var prop = Expression.PropertyOrField(param, propertyOrFieldName);
    if(prop.Type != typeof(TValue)) {
        throw new InvalidOperationException("The property must be " + typeof(TValue).Name);
    }
    var body = Expression.Invoke(func, prop);
    var lambda = Expression.Lambda<Func<TSource, bool>>(body, param);
    return source.Where(lambda);
}

答案 1 :(得分:3)

您知道SqlMethods.Like吗?

答案 2 :(得分:0)

和你一样有问题。 SqlMethods.Like仅在SQL服务器上执行时有效,而不在内存集合上执行。所以我已经制作了一个类似的评估器,可用于收藏 - 请参阅我的博客文章here