This question is an exact duplicate of:
- extend Where for IQueryable 1 answer
I want to extend the Where
to something like this: .WhereEqual("Field", "SomeString")
wich must be equivalent to .Where(p => p.Field== "SomeString")
, here is my code:
public static IQueryable<T> WhereEqual<T>(this IQueryable<T> q, string Field, string Value)
{
var param = Expression.Parameter(typeof(T), "p");
var prop = Expression.Property(param, Field);
var val = Expression.Constant(Value);
var body = Expression.Equal(prop, val);
var exp = Expression.Lambda<Func<T, bool>>(body, param);
Type[] types = new Type[] { q.ElementType, typeof(bool) };
var mce = Expression.Call(
typeof(Queryable),
"Where",
types,
exp
);
return q.Provider.CreateQuery<T>(mce);
}
thanks to the debugger i can see that exp
is set to {p => (p.Field== "SomeString")}
, but the Call
method throws the following exception :
"An exception of type 'System.InvalidOperationException' occurred in System.Core.dll but was not handled in user code, Additional information: 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."
How can I give the Where
the needed arguments ?
Thanks.