.NetCore 扩展封装 Expression<Func<T, bool>> 查询条件遇到的问题
前面的文章封装了查询条件 自己去组装条件,但是对 And Or 这种组合支持很差,但是也不是不能支持,只是要写更多的代码看起来很臃肿
根据 Where(Expression<Func<T, bool>>) 我们直接来处理这个,在处理这个之前其实看了下
Expression这个对象的处理,本生里面是包含了 AndAlso 、 Or 的处理 先来看看这个会遇到什么问题?为什么不行?
比如:
Expression.AndAlso(first,second)
来一段之前的扩展
public static Expression AndExpression(this Expression expression, Expression right)
{
return Expression.AndAlso(expression, right); }
public static Expression OrExpression(this Expression expression, Expression right)
{
return Expression.Or(expression, right); }
public static Expression<Func<T,bool>> ToFilter<T>(this Expression expression)
{
return Expression.Lambda<Func<T, bool>>(expression, Expression.Parameter(typeof(T))); }
本质上没什么不同,最后连接都能拿到相关的表达式
Expression filter= Expression.Constant(true, typeof(bool));
if (!string.IsNullOrEmpty(username))
{
filter = filter.AndExpression(new UosoConditions {
Key = "UserName",
Operator = UosoOperatorEnum.Contains,
Value = username,
ValueType = "string"
}.Parser<IdentityUser>());
}
按照如上写法多写几个条件,2个查询条件,2个值,感觉没问题, 但是运行到Where的时候报错误 表到时Parameter参数的个数对应不上表达式参数的个数,参数丢失了?
参数的值跟随表达式,在组合的时候需要重新组合参数,如果直接组合表达式,参数不会发生变化所以需要处理下参数问题,对(Expression<Func<T, bool>>) 的扩展就迎刃而解了
正确的处理方式:
public static class ExpressionExtensions
{
/// <summary>
/// 添加And条件
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="first"></param>
/// <param name="second"></param>
/// <returns></returns>
public static Expression<Func<T, bool>> And<T>(
this Expression<Func<T, bool>> first,
Expression<Func<T, bool>> second)
{
return first.AndAlso<T>(second, Expression.AndAlso);
}
/// <summary>
/// 添加Or条件
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="first"></param>
/// <param name="second"></param>
/// <returns></returns>
public static Expression<Func<T, bool>> Or<T>(
this Expression<Func<T, bool>> first,
Expression<Func<T, bool>> second)
{
return first.AndAlso<T>(second, Expression.OrElse);
}
/// <summary>
/// 合并表达式以及参数
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="expr1"></param>
/// <param name="expr2"></param>
/// <param name="func"></param>
/// <returns></returns>
private static Expression<Func<T, bool>> AndAlso<T>(
this Expression<Func<T, bool>> expr1,
Expression<Func<T, bool>> expr2,
Func<Expression, Expression, BinaryExpression> func)
{
var parameter = Expression.Parameter(typeof(T)); var leftVisitor = new ReplaceExpressionVisitor(expr1.Parameters[], parameter);
var left = leftVisitor.Visit(expr1.Body); var rightVisitor = new ReplaceExpressionVisitor(expr2.Parameters[], parameter);
var right = rightVisitor.Visit(expr2.Body); return Expression.Lambda<Func<T, bool>>(
func(left, right), parameter); } private class ReplaceExpressionVisitor
: ExpressionVisitor
{
private readonly Expression _oldValue;
private readonly Expression _newValue; public ReplaceExpressionVisitor(Expression oldValue, Expression newValue)
{
_oldValue = oldValue;
_newValue = newValue;
} public override Expression Visit(Expression node)
{
if (node == _oldValue)
return _newValue;
return base.Visit(node);
}
}
}
使用方法就简单多了
Expression<Func<IdentityUser, bool>> filter = u => true;
if (!string.IsNullOrEmpty(username))
{
filter = filter.And(c => c.UserName.Contains(username));
}
if (!string.IsNullOrEmpty(phone))
{
filter = filter.And(c => c.PhoneNumber.Contains(phone));
}
if (!string.IsNullOrEmpty(email))
{
filter = filter.And(c => c.Email.Contains(email));
}
这里值得注意的是 一定要重新赋值到 filter ,按理说扩展了Expression<Func<T, bool>> 也返回了 Expression<Func<T, bool>> 好像可以不用重新赋值,然而这里并不是这样
如果我们直接
filter.And(c => c.UserName.Contains(username));
这样添加 会发现之中都是第一个参数的条件 都是 true,这是为什么呢?
Expression<Func<IdentityUser, bool>> filter = u => true;
下面看下这段代码其实给之前出现错误的原因是一样的?
private static Expression<Func<T, bool>> AndAlso<T>(
this Expression<Func<T, bool>> expr1,
Expression<Func<T, bool>> expr2,
Func<Expression, Expression, BinaryExpression> func)
{
var parameter = Expression.Parameter(typeof(T)); var leftVisitor = new ReplaceExpressionVisitor(expr1.Parameters[], parameter);
var left = leftVisitor.Visit(expr1.Body); var rightVisitor = new ReplaceExpressionVisitor(expr2.Parameters[], parameter);
var right = rightVisitor.Visit(expr2.Body); return Expression.Lambda<Func<T, bool>>(
func(left, right), parameter); }
var parameter = Expression.Parameter(typeof(T)); 是对 T 类中做的反射,本生合并两个带 T 的应该是没问题的,只是因为
与 Expression<Func<IdentityUser, bool>> filter = u => true; 组合后
Expression.Lambda<Func<T, bool>>(
func(left, right), parameter);
一直都是True,导致最后的条件都是返回 True 查询条件就无效了,所以需要重新引用赋值 filter
.NetCore 扩展封装 Expression<Func<T, bool>> 查询条件遇到的问题的更多相关文章
- EF Core 封装方法Expression<Func<TObject, bool>>与Func<TObject, bool>区别
unc<TObject, bool>是委托(delegate) Expression<Func<TObject, bool>>是表达式 Expression编译后就 ...
- lambda表达式Expression<Func<Person, bool>> 、Func<Person, bool>区别
前言: 自己通过lambda表达式的封装,将对应的表达式转成字符串的过程中,对lambda表达式有了新的认识 原因: 很多开发者对lambda表达式Expression<Func<Pers ...
- Expression<Func<TObject, bool>>与Func<TObject, bool>的区别
Func<TObject, bool>是委托(delegate) Expression<Func<TObject, bool>>是表达式 Expression编译后 ...
- Expression<Func<T, bool>>与Func<T, bool>的区别
转自:http://www.cnblogs.com/wow-xc/articles/4952233.html Func<TObject, bool>是委托(delegate) Expres ...
- .NET Core中合并Expression<Func<T,bool>>的正确姿势
这是在昨天的 .NET Core 迁移中遇到的问题,之前在 .NET Framework 中是这样合并 Expression<Func<T,bool>> 的: public s ...
- 表达式拼接Expression<Func<IEntityMapper, bool>> predicate
/// <summary> /// 重写以筛选出当前上下文的实体映射信息 /// </summary> protected override IEnumerable<IE ...
- Expression<Func<T, bool>>
public static Expression<Func<T, bool>> True<T>() { return f => true; } public ...
- 拉姆达表达式 追加 条件判断 Expression<Func<T, bool>>
public static class PredicateBuilder { /// <summary> /// 机关函数应用True时:单个AND有效,多个AND有效:单个OR无效,多个 ...
- Entity Framework 动态构造Lambda表达式Expression<Func<T, bool>>
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; us ...
随机推荐
- 通信对象 System.ServiceModel.Channels.ServiceChannel 无法用于通信,因为其处于“出错”状态。
通信对象 System.ServiceModel.Channels.ServiceChannel 无法用于通信,因为其处于“出错”状态. 在 System.ServiceModel.Channels. ...
- lightgbm原理以及Python代码
原论文: http://papers.nips.cc/paper/6907-lightgbm-a-highly-efficient-gradient-boosting-decision-tree.pd ...
- UOJ#424 【集训队作业2018】count
题意 我们定义长度为\(n\),每个数为\(1\sim m\)之间的整数且\(1\sim m\)都至少出现一次的序列为合法序列.再定义\(pos(l,r)\)表示这个序列的区间\([l,r]\)之间的 ...
- idea log4j 用法
1.导入jar包 这里用的maven导入 <!-- LOGGING begin --> <dependency> <groupId>org.slf4j</gr ...
- Nginx多进程高并发、低时延、高可靠机制缓存代理中的应用
1. 开发背景 现有开源缓存代理中间件有twemproxy.codis等,其中twemproxy为单进程单线程模型,只支持memcache单机版和redis单机版,都不支持集群版功能. 由于twemp ...
- 洛谷 T28312 相对分子质量【2018 6月月赛 T2】 解题报告
T28312 「化学」相对分子质量 题目描述 做化学题时,小\(F\)总是里算错相对分子质量,这让他非常苦恼. 小\(F\)找到了你,请你来帮他算一算给定物质的相对分子质量. 如果你没有学过相关内容也 ...
- UVAlive-7040 color(组合数学,二项式反演)
链接:vjudge 题目大意:有一排方格共 $n$ 个,现在有 $m$ 种颜色,要给这些方格染色,要求相邻两个格子的颜色不能相同.现在问恰好用了 $k$ 种颜色的合法方案数.答案对 $10^9+7$ ...
- 【bzoj4009】 HNOI2015—接水果
http://www.lydsy.com/JudgeOnline/problem.php?id=4009 (题目链接) 题意 给出一颗无根树.有一些路径记为$P_i$,这些路径有两个端点和一个权值$W ...
- Redis与memecache的区别
转载连接: https://www.biaodianfu.com/redis-vs-memcached.html Redis的作者Salvatore Sanfilippo曾经对这两种基于内存的数据存储 ...
- 如何构建 Redis 高可用架构?
温国兵 民工哥技术之路 今天 1 .题记 Redis 是一个开源的使用 ANSI C 语言编写.支持网络.可基于内存亦可持久化的日志型.Key-Value 数据库,并提供多种语言的 API. 如今,互 ...