1

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

0

1 Answer 1

1

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 }
  )
);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for replay, it is working,can you tell me please how can i add "Or" statement to this generated function, that let me to use this function for searching by multiple columns.
Please create a new question and include the code you have so far.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.