所以,这有点复杂。
我有一组规则存储在一个集合里,一个规则包含以下三个属性。
Field, Op, and Data (all strings)
因此,一条规则可能看起来像是“State”,“eq”,“CA”。
我的一般规则是所有规则都要一起使用。但是,如果它们具有相同的字段值,则所有规则都应该使用OR一起使用。这使我们能够说“State”,“eq”,“CA”,或“State”,“eq”,“TX”并且“FirstName”,“eq”,“John”。
问题是,我的当前应用规则的方式不起作用,因为它仅仅使用每个规则来构建linq表达式,导致越来越明确。
var result = rules.Aggregate(_repository.All, (current, rule) => current.ExtendQuery(rule))
ExtendQuery
是我编写的扩展方法,它使用表达式树来生成一个新查询,将当前规则应用于传入查询。(实际上将它们全部连接在一起)。现在,我可以很容易地修改
.Aggregate
行,按字段分组规则,然后为每个字段生成唯一查询,但是如何让它们"OR"而不是"AND"呢?然后,对于这些查询中的每一个,我该如何使它们"AND"在一起呢?使用联合查询吗?
ExtendQuery
看起来像这样。 public static IQueryable<T> ExtendQuery<T>(this IQueryable<T> query, QueryableRequestMessage.WhereClause.Rule rule) where T : class
{
var parameter = Expression.Parameter(typeof(T), "x");
Expression property = Expression.Property(parameter, rule.Field);
var type = property.Type;
ConstantExpression constant;
if (type.IsEnum)
{
var enumeration = Enum.Parse(type, rule.Data);
var intValue = (int)enumeration;
constant = Expression.Constant(intValue);
type = typeof(int);
//Add "Id" by convention, this is all because enum support is lacking at this point in Entity Framework
property = Expression.Property(parameter, rule.Field + "Id");
}
else if(type == typeof(DateTime))
{
constant = Expression.Constant(DateTime.ParseExact(rule.Data, "dd/MM/yyyy", CultureInfo.CurrentCulture));
}
else if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
//This will convert rule.Data to the baseType, not a nullable type (because that won't work)
var converter = TypeDescriptor.GetConverter(type);
var value = converter.ConvertFrom(rule.Data);
constant = Expression.Constant(value);
//We change the type of property to get converted to it's base type
//This is because Expression.GreaterThanOrEqual can't compare a decimal with a Nullable<decimal>
var baseType = type.GetTypeOfNullable();
property = Expression.Convert(property, baseType);
}
else
{
constant = Expression.Constant(Convert.ChangeType(rule.Data, type));
}
switch (rule.Op)
{
case "eq": //Equals
case "ne": //NotEquals
{
var condition = rule.Op.Equals("eq")
? Expression.Equal(property, constant)
: Expression.NotEqual(property, constant);
var lambda = Expression.Lambda(condition, parameter);
var call = Expression.Call(typeof(Queryable), "Where", new[] { query.ElementType }, query.Expression, lambda);
query = query.Provider.CreateQuery<T>(call);
break;
}
case "lt": //Less Than
query = type == typeof (String)
? QueryExpressionString(query, Expression.LessThan, type, property, constant, parameter)
: QueryExpression(query, Expression.LessThan, property, constant, parameter); break;
case "le": //Less Than or Equal To
query = type == typeof (String)
? QueryExpressionString(query, Expression.LessThanOrEqual, type, property, constant, parameter)
: QueryExpression(query, Expression.LessThanOrEqual, property, constant, parameter); break;
case "gt": //Greater Than
query = type == typeof (String)
? QueryExpressionString(query, Expression.GreaterThan, type, property, constant, parameter)
: QueryExpression(query, Expression.GreaterThan, property, constant, parameter); break;
case "ge": //Greater Than or Equal To
query = type == typeof (String)
? QueryExpressionString(query, Expression.GreaterThanOrEqual, type, property, constant, parameter)
: QueryExpression(query, Expression.GreaterThanOrEqual, property, constant, parameter); break;
case "bw": //Begins With
case "bn": //Does Not Begin With
query = QueryMethod(query, rule, type, "StartsWith", property, constant, "bw", parameter); break;
case "ew": //Ends With
case "en": //Does Not End With
query = QueryMethod(query, rule, type, "EndsWith", property, constant, "cn", parameter); break;
case "cn": //Contains
case "nc": //Does Not Contain
query = QueryMethod(query, rule, type, "Contains", property, constant, "cn", parameter); break;
case "nu": //TODO: Null
case "nn": //TODO: Not Null
break;
}
return query;
}
private static IQueryable<T> QueryExpression<T>(
IQueryable<T> query,
Func<Expression, Expression, BinaryExpression> expression,
Expression property,
Expression value,
ParameterExpression parameter
) where T : class
{
var condition = expression(property, value);
var lambda = Expression.Lambda(condition, parameter);
var call = Expression.Call(typeof(Queryable), "Where", new[] { query.ElementType }, query.Expression, lambda);
query = query.Provider.CreateQuery<T>(call);
return query;
}
private static IQueryable<T> QueryExpressionString<T>(
IQueryable<T> query,
Func<Expression, Expression, BinaryExpression> expression,
Type type,
Expression property,
Expression value,
ParameterExpression parameter)
{
var containsmethod = type.GetMethod("CompareTo", new[] { type });
var callContains = Expression.Call(property, containsmethod, value);
var call = expression(callContains, Expression.Constant(0, typeof(int)));
return query.Where(Expression.Lambda<Func<T, bool>>(call, parameter));
}
private static IQueryable<T> QueryMethod<T>(
IQueryable<T> query,
QueryableRequestMessage.WhereClause.Rule rule,
Type type,
string methodName,
Expression property,
Expression value,
string op,
ParameterExpression parameter
) where T : class
{
var containsmethod = type.GetMethod(methodName, new[] { type });
var call = Expression.Call(property, containsmethod, value);
var expression = rule.Op.Equals(op)
? Expression.Lambda<Func<T, bool>>(call, parameter)
: Expression.Lambda<Func<T, bool>>(Expression.IsFalse(call), parameter);
query = query.Where(expression);
return query;
}