rdnti softs
rdnti softs

Reputation: 39

Dynamic Linq Where with Lambda Expression generates Error

I have a dynamic Linq query

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

This function generates an error which is the following:

No generic method 'Where' on type 'System.Linq.Queryable' is compatible with the supplied type arguments and arguments. No type arguments should be provided if the method is non-generic.

An idea on the error, thank you

Upvotes: 1

Views: 301

Answers (1)

Daniel Manta
Daniel Manta

Reputation: 6718

You need to pass Func<T, bool> because the predicate for Where method is a function to test each element for a condition and type of input elements is T while the output is bool.

Finally, when creating the lambda expression, pass the same parameter used in queryExpr, otherwise it'd raise error variable not found. So instead of pe, it is parameter.

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

Upvotes: 1

Related Questions