EntityFramework动态多条件查询与Lambda表达式树

    在常规的信息系统中, 我们有需要动态多条件查询的情况, 例如UI上有多个选择项可供用户选择多条件查询数据. 
那么在.net平台Entity Framework下, 我们用Lambda表达式树如何实现, 这里我们需要一个PredicateBuilder的UML类图:

EntityFramework动态多条件查询与Lambda表达式树_第1张图片

实现的代码是这样的:

   /// 
    /// Enables the efficient, dynamic composition of query predicates.
    /// 
    public static class PredicateBuilder
    {
        /// 
        /// Creates a predicate that evaluates to true.
        /// 
        public static Expressionbool>> True() { return param => true; }
 
        /// 
        /// Creates a predicate that evaluates to false.
        /// 
        public static Expressionbool>> False() { return param => false; }
 
        /// 
        /// Creates a predicate expression from the specified lambda expression.
        /// 
        public static Expressionbool>> Create(Expressionbool>> predicate) { return predicate; }
 
        /// 
        /// Combines the first predicate with the second using the logical "and".
        /// 
        public static Expressionbool>> And(this Expressionbool>> first, Expressionbool>> second)
        {
            return first.Compose(second, Expression.AndAlso);
        }
 
        /// 
        /// Combines the first predicate with the second using the logical "or".
        /// 
        public static Expressionbool>> Or(this Expressionbool>> first, Expressionbool>> second)
        {
            return first.Compose(second, Expression.OrElse);
        }
 
        /// 
        /// Negates the predicate.
        /// 
        public static Expressionbool>> Not(this Expressionbool>> expression)
        {
            var negated = Expression.Not(expression.Body);
            return Expression.Lambdabool>>(negated, expression.Parameters);
        }
 
        /// 
        /// Combines the first expression with the second using the specified merge function.
        /// 
        static Expression Compose(this Expression first, Expression second, Func merge)
        {
            // zip parameters (map from parameters of second to parameters of first)
            var map = first.Parameters
                .Select((f, i) => new { f, s = second.Parameters[i] })
                .ToDictionary(p => p.s, p => p.f);
 
            // replace parameters in the second lambda expression with the parameters in the first
            var secondBody = ParameterRebinder.ReplaceParameters(map, second.Body);
 
            // create a merged lambda expression with parameters from the first expression
            return Expression.Lambda(merge(first.Body, secondBody), first.Parameters);
        }
 
        /// 
        /// ParameterRebinder
        /// 
        class ParameterRebinder : ExpressionVisitor
        {
            /// 
            /// The ParameterExpression map
            /// 
            readonly Dictionary map;
 
            /// 
            /// Initializes a new instance of the  class.
            /// 
            /// The map.
            ParameterRebinder(Dictionary map)
            {
                this.map = map ?? new Dictionary();
            }
 
            /// 
            /// Replaces the parameters.
            /// 
            /// The map.
            /// The exp.
            /// Expression
            public static Expression ReplaceParameters(Dictionary map, Expression exp)
            {
                return new ParameterRebinder(map).Visit(exp);
            }
 
            /// 
            /// Visits the parameter.
            /// 
            /// The p.
            /// Expression
            protected override Expression VisitParameter(ParameterExpression p)
            {
                ParameterExpression replacement;
 
                if (map.TryGetValue(p, out replacement))
                {
                    p = replacement;
                }
 
                return base.VisitParameter(p);
            }
        }
    }


UnitTest的片断代码, 一个产品查询的场景:

            var myProduct=pr.Repository.Find(
                  BuildFindByAllQuery(productName, beignUpdateDate, endUpdateDate) ,
                e => e.UpdatedTime,
                pageIndex,
                pageSize);
 
            Assert.IsTrue(myProduct.Count>0);

UnitTest使用到 生成查询条件 的 私有方法:

         /// 
         /// Builds the find by all query.
         /// 
         private static Expressionbool>> BuildFindByAllQuery(string productName,DateTime? beignUpdateDate, DateTime? endUpdateDate)
         {
 
             var list = new Listbool>>>();
 
             if (!string.IsNullOrEmpty(productName)) list.Add(c => c.ProductName == productName);
 
             if (beignUpdateDate != null) list.Add(c => c.UpdatedTime >= beignUpdateDate);
 
             if (endUpdateDate != null) list.Add(c => c.UpdatedTime <= endUpdateDate);
 
             //Add more condition
             Expressionbool>> productQueryTotal = null;
 
             foreach (var expression in list)
             {
                 productQueryTotal = expression.And(expression);
             }
             return productQueryTotal;
         }

上面的方法中由三个条件动态组成,  一个是匹配productName, 另两个是beginUpdateDate与endUpdateDate. 在判断它们是否为时, 构建最终查询条件集合.

最后把结果传给某个Repository类, 完成相应的数据访问. 

你可能感兴趣的:(MVC技巧,entity,framework)