我使用类似的方法,在查询中添加过滤器。
public static Expression<Func<TypeOfParent, bool>> PropertyStartsWith<TypeOfParent, TypeOfPropery>(PropertyInfo property, TypeOfPropery value)
{
var parent = Expression.Parameter(typeof(TypeOfParent));
MethodInfo method = typeof(string).GetMethod("StartsWith",new Type[] { typeof(TypeOfPropery) });
var expressionBody = Expression.Call(Expression.Property(parent, property), method, Expression.Constant(value));
return Expression.Lambda<Func<TypeOfParent, bool>>(expressionBody, parent);
}
使用方法:针对属性名称匹配Key的属性应用过滤器,并使用提供的值Value。
public static IQueryable<T> ApplyParameters<T>(this IQueryable<T> query, List<GridParameter> gridParameters)
{
var propertyInfo = typeof(T).GetProperty(parameter.Key);
query = query.Where(PropertyStartsWith<T, string>(propertyInfo, parameter.Value));
}
是的,这种方法也适用于包含:
public static Expression<Func<TypeOfParent, bool>> PropertyContains<TypeOfParent, TypeOfPropery>(PropertyInfo property, TypeOfPropery value)
{
var parent = Expression.Parameter(typeof(TypeOfParent));
MethodInfo method = typeof(string).GetMethod("Contains", new Type[] { typeof(TypeOfPropery) });
var expressionBody = Expression.Call(Expression.Property(parent, property), method, Expression.Constant(value));
return Expression.Lambda<Func<TypeOfParent, bool>>(expressionBody, parent);
}
通过这两个例子,您可以更轻松地理解我们如何通过名称调用各种不同的方法。