为IQueryable扩展Where方法

时间:2014-07-20 14:27:00

标签: c# linq entity-framework linq-to-entities entity-framework-6

我想将Where扩展为类似的内容:.WhereEqual("Field", "SomeString")必须等同于.Where(p => p.Field== "SomeString"),这是我的代码:

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")},但Call方法会抛出以下异常:

  

&#34;类型&#39; System.InvalidOperationException&#39;的例外情况发生在   System.Core.dll但未在用户代码中处理,附加   信息:没有通用方法&#39; Where&#39; on type&#39; System.Linq.Queryable&#39;   与提供的类型参数和参数兼容。没有类型   如果方法是非泛型的,则应提供参数。&#34;

如何向Where提供所需的参数?

感谢。

1 个答案:

答案 0 :(得分:2)

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