EF Expression 扩展

Posted jasonlai2016

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了EF Expression 扩展相关的知识,希望对你有一定的参考价值。

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("2"));
expr = expr.Or(n => n.PID > 5);
context.表名.Where(expr).ToList()

 

以上是关于EF Expression 扩展的主要内容,如果未能解决你的问题,请参考以下文章

APS.NET MVC + EF (04)---路由和数据传递

EF添加关联的提示问题:映射从第 260 行开始的片段时有问题:

Expression 表达式

EF6 自定义迁移表名

第十九节: 结合表达式目录树来封装EF的BaseDal层的方法

System.Core 错误:使用 C# Entity Framework 和 Linq 和 Expression 的“代码应该无法访问”