【问题标题】:Dynamic Linq Where with Lambda Expression generates Error使用 Lambda 表达式生成错误的动态 Linq
【发布时间】:2020-10-11 19:03:23
【问题描述】:

我有一个动态 Linq 查询

    public static IQueryable<T> WhereHelper<T>(this IQueryable<T> source, string property, string propertyValue) where T : class
    {
        //STEP 1: Verify the property is valid
        var searchProperty = typeof(T).GetProperty(property);
         //STEP 2: Create the OrderBy property selector
        var parameter = Expression.Parameter(typeof(T), "o");

        MemberExpression member = Expression.Property(parameter, property);
        MethodInfo method = typeof(string).GetMethod("Contains", new[] { typeof(string) });
        ConstantExpression constant = Expression.Constant(propertyValue);
        MethodCallExpression queryExpr = Expression.Call(member, method, constant);
                    
        ParameterExpression pe = Expression.Parameter(typeof(string), property);

        MethodCallExpression whereCallExpression = Expression.Call(
        typeof(Queryable),
        "Where",
        new Type[] { source.ElementType },
        source.Expression,
        Expression.Lambda<Func<string, bool>>(queryExpr, new ParameterExpression[] { pe }));

        return source.Provider.CreateQuery<T>(whereCallExpression);
    }

这个函数会产生如下错误:

“System.Linq.Queryable”类型上没有通用方法“Where” 与提供的类型参数和参数兼容。无类型 如果方法是非泛型的,则应提供参数。

关于错误的想法,谢谢

【问题讨论】:

    标签: c# linq


    【解决方案1】:

    您需要传递Func&lt;T, bool&gt;,因为Where 方法的谓词是一个函数,用于测试每个元素的条件,输入元素的类型是T,而输出是bool

    最后,在创建 lambda 表达式时,传递 queryExpr 中使用的相同参数,否则会引发错误变量未找到。所以不是pe,而是parameter

    MethodCallExpression whereCallExpression = Expression.Call(
      typeof(Queryable),
      "Where",
      new Type[] { source.ElementType },
      source.Expression,
      Expression.Lambda<Func<T, bool>>(
          queryExpr, 
          new ParameterExpression[] { parameter }
      )
    );
    

    【讨论】:

    • 感谢重播,它正在工作,你能告诉我如何在这个生成的函数中添加“或”语句,让我使用这个函数进行多列搜索。
    • 请创建一个新问题并包含您目前拥有的代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-20
    相关资源
    最近更新 更多