一、简介
当查询比较复杂时,需要很多判断或者跨方法传递参数时使用
二、扩展类
1 /// <summary> 2 /// Expression表达式扩展操作类 3 /// 调用方法:repository.GetAll().AsExpandable().Where(predicate) 4 /// </summary> 5 public static class ExpressionExtensions 6 { 7 /// <summary> 8 /// 以特定的条件运行组合两个Expression表达式 9 /// </summary> 10 /// <typeparam name="T">表达式的主实体类型</typeparam> 11 /// <param name="first">第一个Expression表达式</param> 12 /// <param name="second">要组合的Expression表达式</param> 13 /// <param name="merge">组合条件运算方式</param> 14 /// <returns>组合后的表达式</returns> 15 public static Expression<T> Compose<T>(this Expression<T> first, Expression<T> second, 16 Func<Expression, Expression, Expression> merge) 17 { 18 var map = 19 first.Parameters.Select((f, i) => new { f, s = second.Parameters[i] }).ToDictionary(p => p.s, p => p.f); 20 var secondBody = ParameterRebinder.ReplaceParameters(map, second.Body); 21 return Expression.Lambda<T>(merge(first.Body, secondBody), first.Parameters); 22 } 23 24 /// <summary> 25 /// 以 Expression.AndAlso 组合两个Expression表达式 26 /// </summary> 27 /// <typeparam name="T">表达式的主实体类型</typeparam> 28 /// <param name="first">第一个Expression表达式</param> 29 /// <param name="second">要组合的Expression表达式</param> 30 /// <returns>组合后的表达式</returns> 31 public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> first, 32 Expression<Func<T, bool>> second) 33 { 34 return first.Compose(second, Expression.AndAlso); 35 } 36 37 /// <summary> 38 /// 以 Expression.OrElse 组合两个Expression表达式 39 /// </summary> 40 /// <typeparam name="T">表达式的主实体类型</typeparam> 41 /// <param name="first">第一个Expression表达式</param> 42 /// <param name="second">要组合的Expression表达式</param> 43 /// <returns>组合后的表达式</returns> 44 public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> first, 45 Expression<Func<T, bool>> second) 46 { 47 return first.Compose(second, Expression.OrElse); 48 } 49 50 private class ParameterRebinder : ExpressionVisitor 51 { 52 private readonly Dictionary<ParameterExpression, ParameterExpression> _map; 53 54 private ParameterRebinder(Dictionary<ParameterExpression, ParameterExpression> map) 55 { 56 _map = map ?? new Dictionary<ParameterExpression, ParameterExpression>(); 57 } 58 59 public static Expression ReplaceParameters(Dictionary<ParameterExpression, ParameterExpression> map, 60 Expression exp) 61 { 62 return new ParameterRebinder(map).Visit(exp); 63 } 64 65 protected override Expression VisitParameter(ParameterExpression node) 66 { 67 ParameterExpression replacement; 68 if (_map.TryGetValue(node, out replacement)) 69 node = replacement; 70 return base.VisitParameter(node); 71 } 72 } 73 }
三、如何使用
1.关于引用
using System.Linq;
using System.Linq.Expressions;
using LinqKit;
还需要引入扩展类的命名空间
2.使用示例
1 Expression<Func<User, bool>> pre; 2 pre = s => s.NickName.Contains("李"); 3 pre = pre.Or(s => s.NickName.Contains("陈")); 4 pre = pre.And(s => s.CompanyId == "1"); 5 6 var data = _userRepository.GetAll().AsExpandable().Where(pre);