问题描述

项目中使用AutoMapper进行VO&DTO&Entity的互相映射,但是默认Map方法不支持Expression的转换。如

Expression<Func<Entity,bool>> fun = _ => _.A == "A";

希望转换成

Expression<Func<Dto,bool>> fun = _ => _.A == "A";

似乎解决方案就是解析ExpressionTree并映射替换节点。正好找到了人家的提问和解决方案

http://stackoverflow.com/questions/7424501/automapper-for-funcs-between-selector-types

改造一下支持泛型,代码如下:

 public static class FunctionCompositionExtensions
{
private static ConcurrentDictionary<Tuple<Type, Type>, Tuple<MethodInfo, Expression>> dictionary = new ConcurrentDictionary<Tuple<Type, Type>, Tuple<MethodInfo, Expression>>();
private static MethodInfo method = typeof(FunctionCompositionExtensions).GetMethod("Compose", BindingFlags.NonPublic | BindingFlags.Static); public static Expression<Func<D, bool>> MapExpression<S, D>(this Expression<Func<S, bool>> selector)
{
var bulidMethod = dictionary.GetOrAdd(new Tuple<Type, Type>(typeof(S), typeof(D)), _ =>
{
var expression = Mapper.Engine.CreateMapExpression<D, S>();
return new Tuple<MethodInfo, Expression>(method.MakeGenericMethod(typeof(D), typeof(bool), typeof(S)), expression);
});
return bulidMethod.Item1.Invoke(null, new[] { selector, bulidMethod.Item2 }) as Expression<Func<D, bool>>; } static Expression<Func<X, Y>> Compose<X, Y, Z>(this Expression<Func<Z, Y>> outer, Expression<Func<X, Z>> inner)
{
return Expression.Lambda<Func<X, Y>>(
ParameterReplacer.Replace(outer.Body, outer.Parameters[0], inner.Body),
inner.Parameters[0]);
} static Expression<Predicate<X>> ComposePredicate<X, Z>(this Expression<Predicate<Z>> outer, Expression<Func<X, Z>> inner)
{
return Expression.Lambda<Predicate<X>>(
ParameterReplacer.Replace(outer.Body, outer.Parameters[0], inner.Body),
inner.Parameters[0]);
}
} class ParameterReplacer : ExpressionVisitor
{
private ParameterExpression _parameter;
private Expression _replacement; private ParameterReplacer(ParameterExpression parameter, Expression replacement)
{
_parameter = parameter;
_replacement = replacement;
} public static Expression Replace(Expression expression, ParameterExpression parameter, Expression replacement)
{
return new ParameterReplacer(parameter, replacement).Visit(expression);
} protected override Expression VisitParameter(ParameterExpression parameter)
{
if (parameter == _parameter)
{
return _replacement;
}
return base.VisitParameter(parameter);
}
}

测试

public class Entity
{
public string A { get; set; }
} public class Dto
{
public string A { get; set; }
} Mapper.CreateMap<Entity, Dto>();
Mapper.CreateMap<Dto, Entity>(); var list = new List<Dto>()
{
new Dto() {A = "A"},
new Dto() {A = "B"},
new Dto() {A = "C"},
new Dto() {A = "D"},
new Dto() {A = "E"},
}; //Predicate<Entity> fun = _ => _.A =="A";
Expression<Func<Entity,bool>> funEntity = _ => _.A == "A"; var query = list.Where(funEntity.MapExpression<Entity, Dto>().Compile());
Assert.True(query.Count() == 1); Expression<Func<Entity, bool>> funEntity2 = _ => _.A == "F";
var query2 = list.Where(funEntity2.MapExpression<Entity, Dto>().Compile());
Assert.True(query2.Count() == 0);

AutoMapper映射ExpressionTree的更多相关文章

  1. 配置AutoMapper映射规则《转》

    配置AutoMapper映射规则 AutoMapper是基于约定的,因此在实用映射之前,我们需要先进行映射规则的配置. public class Source { public int SomeVal ...

  2. ASP.NET Core搭建多层网站架构【8.2-使用AutoMapper映射实体对象】

    2020/01/29, ASP.NET Core 3.1, VS2019, AutoMapper.Extensions.Microsoft.DependencyInjection 7.0.0 摘要:基 ...

  3. 使用 AutoMapper 映射 IDataReader、DataSet、DataTable 到实体类

    AutoMapper是一个.NET的对象映射工具. 项目地址:https://github.com/AutoMapper/AutoMapper. 帮助文档:https://github.com/Aut ...

  4. 一文为你详细讲解对象映射库【AutoMapper】所支持场景

    前言 在AutoMapper未出世前,对象与对象之间的映射,我们只能通过手动为每个属性一一赋值,时间长了不仅是我们而且老外也觉得映射代码很无聊啊.这个时候老外的所写的强大映射库AutoMapper横空 ...

  5. .NET CORE 中使用AutoMapper进行对象映射

    简介 AutoMapper uses a fluent configuration API to define an object-object mapping strategy. AutoMappe ...

  6. NetCore+AutoMapper多个对象映射到一个Dto对象

    目录 一. 定义源映射类和被映射类DTO二.注入AutoMapper三.配置映射四.写测试 一.定义源映射对象 为了体现AutoMapper映射特性,在SocialAttribute中的Name属性没 ...

  7. 在 ASP.NET Core 项目中使用 AutoMapper 进行实体映射

    一.前言 在实际项目开发过程中,我们使用到的各种 ORM 组件都可以很便捷的将我们获取到的数据绑定到对应的 List<T> 集合中,因为我们最终想要在页面上展示的数据与数据库实体类之间可能 ...

  8. ASP.NET Core Web 应用程序系列(五)- 在ASP.NET Core中使用AutoMapper进行实体映射

    本章主要简单介绍下在ASP.NET Core中如何使用AutoMapper进行实体映射.在正式进入主题之前我们来看下几个概念: 1.数据库持久化对象PO(Persistent Object):顾名思义 ...

  9. ASP.NET CORE 中使用AutoMapper进行对象映射

    ASP.NET CORE 中使用AutoMapper进行对象映射 1.什么是AutoMapper? AutoMapper是基于对象到对象约定的映射工具,常用于(但并不仅限制于)把复杂的对象模型转为DT ...

随机推荐

  1. Jquery实现ready()的源码

    function bindReady(){ if ( readyBound ) return; readyBound = true; // Mozilla, Opera and webkit nigh ...

  2. CLR via C#深解笔记六 - 泛型

    面向对象编程一个好处就是“代码重用”,极大提高了开发效率.如是,可以派生出一个类,让它继承基类的所有能力,派生类只需要重写虚方法,或添加一些新的方法,就可以定制派生类的行为,使之满足开发人员的需求. ...

  3. Android 使用NDK编译sipdroid Library

    sipdroid是一款开源的运行于Android平台上的voip,目前支持音频和视频通话: 项目拖管地址:http://code.google.com/p/sipdroid/ 下载源代码,导入ecli ...

  4. C#获取内网和外网IP

    写了个小客户端,里面用到了获取内网和外网的IP地址,代码如下: // InnerIP var ipHost = Dns.Resolve(Dns.GetHostName()); ]; innerIP = ...

  5. easyui textbox event 添加

    $('#tt').textbox({ inputEvents:$.extend({},$.fn.textbox.defaults.inputEvents,{ keyup:function(e){ co ...

  6. transition & transform

    transition: 过渡时间 被改变属性 执行函数 延迟时间 transition:width 1s,height 2s 1s; transform: 平移(translate).缩放(scale ...

  7. Netty5 + Protobuf 使用

    1. 安装开发环境 1.1 Netty环境 这里我使用Netty5.0.0版本 到这里下载即可http://netty.io/ 下载netty-all-5.0.0.Alpha2.jar 这个jar包简 ...

  8. 【转载】关于Embedded Linux启动的经典问题

    转载自:http://linux.chinaunix.net/techdoc/install/2009/04/13/1107608.shtml 发信人: armlinux (armlinux), 信区 ...

  9. Mysql 修改密码及重置密码方法

    修改密码: //选择数据库 use mysql; //修改密码 update user set password=password('新密码') where user='root'; //立即生效 f ...

  10. fis3使用环境

    1.全局安装nodejs 2.安装http-server npm install http-server -g 3.安装fis3 npm install -g fis3 如要限制版本号写法是:npm ...