EF Expression 扩展
2024-10-08 11:00:42
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions; namespace HYS.Fee.AppSrv
{
/// <summary>
/// 数据库上下文
/// </summary>
public static class PredicateBuilder
{
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);
}
} 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);
}
}
}
用法:
Expression<Func<表名, bool>> expr = n => true;
expr = expr.And(n => n.PNAME.Contains(""));
expr = expr.Or(n => n.PID > );
context.表名.Where(expr).ToList()
最新文章
- 开源协议:LGPL协议、OSGi协议---打酱油的日子
- 作业三:WC项目
- [xsd学习]复合元素
- Black Box 分类: POJ 栈和队列 2015-08-05 14:07 2人阅读 评论(0) 收藏
- python小算法(一)
- homework_08
- php中位运算的应用:货品的状态
- SVN版本回滚~
- akoj-1267-独木舟上的荡漾
- FastDfs上传图片
- C/C++面试题:编写类String的构造函数、析构函数和赋值函数。
- Cocos Creator学习五:触摸和重力传感响应事件
- MyEclipse 编译错误 web项目中的 js,jsp报错 更改
- nginx 301重定向一种实现方法
- mybatis-plus快速入门使用
- grunt的用法一
- 003-SqlHelper.cs/Web.config
- 使用Maven清理项目
- jQuery事件处理(四)
- STL_容器共通能力
热门文章
- script放在body和放在head的区别
- 关于python 的 __future__
- nginx的学习
- resize2fs: 报错
- B. Game with string 思维问题转化
- 2019年9月2日,亲自最新JDK12.0.2和JRE1.8.0的下载和配置(64bit),被其他教程坑了几圈忍不住自己写一篇
- PMP概略学习上--基本思想和概念
- 题解 P5530 [BalticOI 2002]双调路径
- leetcode78.子集➕90.子集2
- Bugku-CTF之本地包含( 60)