Extend the Where method for IQueryable [duplicate]

萝らか妹 提交于 2019-12-25 03:22:51

问题


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.


回答1:


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


        return System.Linq.Queryable.Where(q, exp);
    }


来源:https://stackoverflow.com/questions/24851434/extend-the-where-method-for-iqueryable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!