using System; using System.Linq; using System.Linq.Expressions; namespace WX.CRM.Common { public static class QueryHelper { public static IQueryable Filter(this IQueryable queryable, Expression> expression) { expression = ValidateExpression(expression); if (expression == null) return queryable; return queryable.Where(expression); } public static Expression> ValidateExpression(Expression> expression) { CheckNull(expression, "expression"); if (GetCriteriaCount(expression) > 1) throw new InvalidOperationException(String.Format("仅允许添加一个条件,条件:{0}", expression)); object value = GetValue(expression); if (value == null) return null; if (string.IsNullOrWhiteSpace(value.ToString())) return null; return expression; } public static int GetCriteriaCount(LambdaExpression expression) { if (expression == null) return 0; string result = expression.ToString().Replace("AndAlso", "|").Replace("OrElse", "|"); return result.Split('|').Count(); } public static object GetValue(LambdaExpression expression) { if (expression == null) return null; Expression getexpression = GetBinaryExpression(expression); BinaryExpression binaryExpression = getexpression as BinaryExpression; if (binaryExpression != null) return GetBinaryValue(binaryExpression); MethodCallExpression callExpression = getexpression as MethodCallExpression; if (callExpression != null) return GetMethodValue(callExpression); return null; } private static Expression GetBinaryExpression(LambdaExpression expression) { var binaryExpression = expression.Body as BinaryExpression; if (binaryExpression != null) return binaryExpression; var unaryExpression = expression.Body as UnaryExpression; if (unaryExpression != null) { var OperandBinary = unaryExpression.Operand as BinaryExpression; if (OperandBinary != null) return OperandBinary; var OperandMethod = unaryExpression.Operand as MethodCallExpression; if (OperandMethod != null) return OperandMethod; } MethodCallExpression callExpression = expression.Body as MethodCallExpression; if (callExpression != null) { return callExpression; } return null; } private static object GetBinaryValue(BinaryExpression binaryExpression) { var unaryExpression = binaryExpression.Right as UnaryExpression; if (unaryExpression != null) return GetConstantValue(unaryExpression.Operand); return GetConstantValue(binaryExpression.Right); } private static object GetConstantValue(Expression expression) { var constantExpression = expression as ConstantExpression; if (constantExpression != null) return constantExpression.Value; return null; } private static object GetMethodValue(MethodCallExpression callExpression) { var argumentExpression = callExpression.Arguments.FirstOrDefault(); return GetConstantValue(argumentExpression); } public static void CheckNull(Expression> expression, string paraName) { if (expression == null) throw new ArgumentException(paraName); } } }