Entity Framework 动态构造Lambda表达式Expression<Func<T, bool>>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

namespace ElegantWM.Tools
{
    public class ParameterRebinder : ExpressionVisitor
    {
        private readonly Dictionary<ParameterExpression, ParameterExpression> map;
        public ParameterRebinder(Dictionary<ParameterExpression, ParameterExpression> map)
        {
            this.map = map ?? new Dictionary<ParameterExpression, ParameterExpression>();
        }
        public static Expression ReplaceParameters(Dictionary<ParameterExpression, ParameterExpression> map, Expression exp)
        {
            return new ParameterRebinder(map).Visit(exp);
        }
        protected override Expression VisitParameter(ParameterExpression p)
        {
            ParameterExpression replacement;
            if (map.TryGetValue(p, out replacement))
            {
                p = replacement;
            }
            return base.VisitParameter(p);
        }
    }

    public static class PredicateExtensions
    {
        public static Expression<Func<T, bool>> True<T>() { return f => true; }
        public static Expression<Func<T, bool>> False<T>() { return f => false; }
        public static Expression<T> Compose<T>(this Expression<T> first, Expression<T> second, Func<Expression, Expression, Expression> merge)
        {
            // build parameter 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 parameters from the first  
            var secondBody = ParameterRebinder.ReplaceParameters(map, second.Body);

            // apply composition of lambda expression bodies to parameters from the first expression   
            return Expression.Lambda<T>(merge(first.Body, secondBody), first.Parameters);
        }

        public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
        {
            return first.Compose(second, Expression.And);
        }

        public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
        {
            return first.Compose(second, Expression.Or);
        }
    }
}

使用方法:

Expression<Func<WMS_User, bool>> Conditions = PredicateExtensions.True<WMS_User>();
if (ids != null)
   Conditions = Conditions.And(u => u.UserOrgIds.Any(o => ids.Contains(o.OrgId)));
if (Cds != null && Cds.Length > 0)
   Conditions = Conditions.And(u => u.UserName.Contains(Cds)|| u.NickName.Contains(Cds) );

EF直接可以使用,例如DBSET.Where(Condtions)

过程中发现网上误传一种方案:DbSet.Where(Func<T,bool>)该方式返回的是IEnumerable,也就是说已经发送到数据库执行了,那么如果我们再在此基础上做分页的话就是基于内存的分页,谨记。

而上面提供的这个方法,则调用的是DbSet.where(Expression<Func<T,bol>>)会等所有条件构造完成后在到数据库里取数据,符合要求。

posted @ 2013-07-11 23:15  jackchain  阅读(2352)  评论(0编辑  收藏  举报