【发布时间】:2014-07-20 12:34:14
【问题描述】:
我需要将IQueryable 的Where 方法扩展为类似这样:
.WhereEx("SomeProperty", "==", "value")
我不知道这是否可能,但我在 SO 中找到了这个:Unable to sort with property name in LINQ OrderBy
我试过这个答案,看起来很有趣(Ziad 的答案):
using System.Linq;
using System.Linq.Expressions;
using System;
namespace SomeNameSpace
{
public static class SomeExtensionClass
{
public static IQueryable<T> OrderByField<T>(this IQueryable<T> q, string SortField, bool Ascending)
{
var param = Expression.Parameter(typeof(T), "p");
var prop = Expression.Property(param, SortField);
var exp = Expression.Lambda(prop, param);
string method = Ascending ? "OrderBy" : "OrderByDescending";
Type[] types = new Type[] { q.ElementType, exp.Body.Type };
var mce = Expression.Call(typeof(Queryable), method, types, q.Expression, exp);
return q.Provider.CreateQuery<T>(mce);
}
}
}
Where 方法可以做同样的事情吗?
谢谢。
更新:
我现在可以设置一个表达式以传递给 Call 方法,但我得到以下异常:“类型 'System.Linq.Queryable' 上没有通用方法 'Where' 与提供的类型参数和参数兼容. 如果方法是非泛型的,则不应提供类型参数。"
这是我的代码:
public static IQueryable<T> WhereEx<T>(this IQueryable<T> q, string Field, string Operator, 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);
}
请注意,我还没有使用 Operator 参数,而是使用 Equal 进行调试。
有人可以帮我解决这个问题吗?
【问题讨论】:
标签: c# linq entity-framework linq-to-entities entity-framework-6