【发布时间】:2009-10-31 15:43:10
【问题描述】:
如何为Like 子句编写动态LINQ 方法。
供参考,有Dynamic LINQ OrderBy on IEnumerable<T> / IQueryable<T>。我正在寻找一个类似的动态Like 子句。
我有以下类似的扩展方法:
public static IQueryable<T> Like<T>(this IQueryable<T> source, string propertyName,
string keyword)
{
var type = typeof(T);
var property = type.GetProperty(propertyName);
var parameter = Expression.Parameter(type, "p");
var propertyAccess = Expression.MakeMemberAccess(parameter, property);
var constant = Expression.Constant("%" + keyword + "%");
var methodExp = Expression.Call(
null,
typeof(SqlMethods).GetMethod("Like", new[] { typeof(string), typeof(string) }),
propertyAccess,
constant);
var lambda = Expression.Lambda<Func<T, bool>>(methodExp, parameter);
return source.Where(lambda);
}
上述方法报错
方法'Boolean Like(System.String, System.String)'不能在客户端使用;它仅用于转换为 SQL。
从Dynamic LINQ OrderBy on IEnumerable<T> / IQueryable<T>修改的另一种方法:
public static IQueryable<T> ALike<T>(this IQueryable<T> source, string property,
string keyword)
{
string[] props = property.Split('.');
Type type = typeof(T);
ParameterExpression arg = Expression.Parameter(type, "x");
Expression expr = arg;
foreach (string prop in props)
{
// use reflection (not ComponentModel) to mirror LINQ
PropertyInfo pi = type.GetProperty(prop);
expr = Expression.Property(expr, pi);
type = pi.PropertyType;
}
var constant = Expression.Constant("%" + keyword + "%");
var methodExp = Expression.Call(
null,
typeof(SqlMethods).GetMethod("Like", new[] { typeof(string), typeof(string) }),
expr,
constant);
Type delegateType = typeof(Func<,>).MakeGenericType(typeof(T), type);
LambdaExpression lambda = Expression.Lambda(delegateType, methodExp, arg);
object result = typeof(Queryable).GetMethods().Single(
method => method.IsGenericMethodDefinition
&& method.GetGenericArguments().Length == 2
&& method.GetParameters().Length == 2)
.MakeGenericMethod(typeof(T), type)
.Invoke(null, new object[] { source, lambda });
return (IQueryable<T>)result;
}
上述方法报错:
“System.Boolean”类型的表达式不能用于返回类型“System.String”
对此有什么想法吗?
【问题讨论】: