扩展IQueryable的Where方法 [英] Extend the Where method for IQueryable

查看:598
本文介绍了扩展IQueryable的Where方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将 Where 扩展到这样的东西: .WhereEqual(Field,SomeString) .Where(p => p.Field ==SomeString),这里是我的代码:

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

感谢调试器我可以看到 exp 设置为 {p => (p.Field ==SomeString)} ,但调用方法抛出以下异常:

thanks to the debugger i can see that exp is set to {p => (p.Field== "SomeString")}, but the Call method throws the following exception :



System.Core.dll中出现System.InvalidOperationException类型的异常,但未在用户代码中处理,附加
信息:否通用方法'Where'on type'System.Linq.Queryable'
与提供的类型参数和参数兼容,如果方法非泛型,则不应该提供类型
参数。

"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."

如何给哪里需要的参数?

谢谢。

推荐答案

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

这篇关于扩展IQueryable的Where方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆