Entityframework dynamic multi-condition query and Lambda Expression Tree

Source: Internet
Author: User

In conventional information systems, we need dynamic multi-condition queries. For example, there are multiple options on the UI for users to select multiple conditions to query data.
So under the Entity Framework of. NET platform, how can we implement it using the lambda Expression Tree? Here we need a UML class diagram of predicatebuilder:

The implementation code is as follows:

   /// <summary>
    /// Enables the efficient, dynamic composition of query predicates.
    /// </summary>
    public static class PredicateBuilder
    {
        /// <summary>
        /// Creates a predicate that evaluates to true.
        /// </summary>
        public static Expression<Func<T, bool>> True<T>() { return param => true; }
 
        /// <summary>
        /// Creates a predicate that evaluates to false.
        /// </summary>
        public static Expression<Func<T, bool>> False<T>() { return param => false; }
 
        /// <summary>
        /// Creates a predicate expression from the specified lambda expression.
        /// </summary>
        public static Expression<Func<T, bool>> Create<T>(Expression<Func<T, bool>> predicate) { return predicate; }
 
        /// <summary>
        /// Combines the first predicate with the second using the logical "and".
        /// </summary>
        public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
        {
            return first.Compose(second, Expression.AndAlso);
        }
 
        /// <summary>
        /// Combines the first predicate with the second using the logical "or".
        /// </summary>
        public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
        {
            return first.Compose(second, Expression.OrElse);
        }
 
        /// <summary>
        /// Negates the predicate.
        /// </summary>
        public static Expression<Func<T, bool>> Not<T>(this Expression<Func<T, bool>> expression)
        {
            var negated = Expression.Not(expression.Body);
            return Expression.Lambda<Func<T, bool>>(negated, expression.Parameters);
        }
 
        /// <summary>
        /// Combines the first expression with the second using the specified merge function.
        /// </summary>
        static Expression<T> Compose<T>(this Expression<T> first, Expression<T> second, Func<Expression, Expression, Expression> 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<T>(merge(first.Body, secondBody), first.Parameters);
        }
 
        /// <summary>
        /// ParameterRebinder
        /// </summary>
        class ParameterRebinder : ExpressionVisitor
        {
            /// <summary>
            /// The ParameterExpression map
            /// </summary>
            readonly Dictionary<ParameterExpression, ParameterExpression> map;
 
            /// <summary>
            /// Initializes a new instance of the <see cref="ParameterRebinder"/> class.
            /// </summary>
            /// <param name="map">The map.</param>
            ParameterRebinder(Dictionary<ParameterExpression, ParameterExpression> map)
            {
                this.map = map ?? new Dictionary<ParameterExpression, ParameterExpression>();
            }
 
            /// <summary>
            /// Replaces the parameters.
            /// </summary>
            /// <param name="map">The map.</param>
            /// <param name="exp">The exp.</param>
            /// <returns>Expression</returns>
            public static Expression ReplaceParameters(Dictionary<ParameterExpression, ParameterExpression> map, Expression exp)
            {
                return new ParameterRebinder(map).Visit(exp);
            }
 
            /// <summary>
            /// Visits the parameter.
            /// </summary>
            /// <param name="p">The p.</param>
            /// <returns>Expression</returns>
            protected override Expression VisitParameter(ParameterExpression p)
            {
                ParameterExpression replacement;
 
                if (map.TryGetValue(p, out replacement))
                {
                    p = replacement;
                }
 
                return base.VisitParameter(p);
            }
        }
    }


Unittest code snippet, a product query scenario:

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

Unittest uses a private method to generate query conditions:

         /// <summary>
         /// Builds the find by all query.
         /// </summary>
         private static Expression<Func<Product, bool>> BuildFindByAllQuery(string productName,DateTime? beignUpdateDate, DateTime? endUpdateDate)
         {
 
             var list = new List<Expression<Func<Product, bool>>>();
 
             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
             Expression<Func<Product, bool>> productQueryTotal = null;
 
             foreach (var expression in list)
             {
                 productQueryTotal = expression.And(expression);
             }
             return productQueryTotal;
         }

The above method consists of three conditions dynamically. One is to match productname, and the other two are beginupdatedate and endupdatedate. when determining whether they are last, construct the final query condition set.

Finally, pass the result to a repository class to complete the corresponding data access.

Is it easy? I hope it will be helpful for your software development.

Articles you may be interested in:

Recursive Method in Expression Tree
Extended method of ienumerable

Use the LINQ recursive algorithm in. net3.5 to implement concise code

If you want to learn more about software development, please pay attention to my subscription number:

 


Petter Liu
Source: http://www.cnblogs.com/wintersun/
The copyright of this article is shared by the author and the blog Park. You are welcome to repost this article. However, you must retain this statement without the author's consent and provide a clear link to the original article on the article page. Otherwise, you will be held legally liable.
This article is also published in Petter Liu blog, my independent blog.

Entityframework dynamic multi-condition query and Lambda Expression Tree

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.