使用AutoMapper时Expression的转换
此文章为转载:http://www.bubuko.com/infodetail-699735.html
参考链接:
http://q.cnblogs.com/q/34480/ dudu有回复,其中一个链接http://stackoverflow.com/questions/7424501/automapper-for-funcs-between-selector-types可以打开,并且本人主要参考此链接进行修改
下文链接为automapper相关源码
http://www.symbolsource.org/Public/Metadata/NuGet/Project/AutoMapper/3.3.0-ci1017/Release/Unsupported,Version%3Dv0.0/AutoMapper/AutoMapper/Internal/MappingExpression.cs?ImageName=AutoMapper
以下为转载内容:
问题描述
项目中使用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
改造一下支持泛型,代码如下:
#region using namespace using System;
using System.Collections.Concurrent;
using System.Linq.Expressions;
using System.Reflection;
using AutoMapper;
using AutoMapper.QueryableExtensions; #endregion namespace Core
{
public static class FunctionCompositionExtensions
{
private static readonly ConcurrentDictionary<Tuple<Type, Type>, Tuple<MethodInfo, Expression>> Dictionary =
new ConcurrentDictionary<Tuple<Type, Type>, Tuple<MethodInfo, Expression>>(); private static readonly MethodInfo Method = typeof (FunctionCompositionExtensions).GetMethod("Compose",
BindingFlags.NonPublic | BindingFlags.Static); public static Expression<Func<TDestination, bool>> MapExpression<TSource, TDestination>(
this Expression<Func<TSource, bool>> selector)
{
var bulidMethod = Dictionary.GetOrAdd(new Tuple<Type, Type>(typeof (TSource), typeof (TDestination)), _ =>
{
var expression = Mapper.Engine.CreateMapExpression<TDestination, TSource>();
return new Tuple<MethodInfo, Expression>(
Method.MakeGenericMethod(typeof (TDestination), typeof (bool), typeof (TSource)), expression);
});
return
bulidMethod.Item1.Invoke(null, new object[] {selector, bulidMethod.Item2}) as
Expression<Func<TDestination, bool>>;
} public static Expression<Func<TX, TY>> Compose<TX, TY, TZ>(this Expression<Func<TZ, TY>> outer,
Expression<Func<TX, TZ>> inner)
{
return Expression.Lambda<Func<TX, TY>>(
ParameterReplacer.Replace(outer.Body, outer.Parameters[], inner.Body),
inner.Parameters[]);
} public static Expression<Predicate<TX>> ComposePredicate<TX, TZ>(this Expression<Predicate<TZ>> outer,
Expression<Func<TX, TZ>> inner)
{
return Expression.Lambda<Predicate<TX>>(
ParameterReplacer.Replace(outer.Body, outer.Parameters[], inner.Body),
inner.Parameters[]);
}
} class ParameterReplacer : ExpressionVisitor
{
private readonly ParameterExpression _parameter;
private readonly 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() == ); Expression<Func<Entity, bool>> funEntity2 = _ => _.A == "F";
var query2 = list.Where(funEntity2.MapExpression<Entity, Dto>().Compile());
Assert.True(query2.Count() == );
使用AutoMapper时Expression的转换的更多相关文章
- 一对多关系domain Model中设置使用AutoMapper时出错
在使用AutoMapper时,把数据从VO-PO时显示如下错误,错误提示说在一对多关系中已将集合设置为EntityCollection,那么这个是为什么呢. 看下action中的代码,我们可以发现这是 ...
- 使用C/C++,赋值运算时发生的转换
使用C/C++,赋值运算时发生的转换主要有以下四种情况 一: 两边类型不同: 结果: 自动完成类型转换! 二: 长数赋给短数: 结果: 截取长数的低位送给短数! 三: 短数赋给长数: 结果: 原来是什 ...
- PowerDesigner中转换物理模型时的命名转换
原文:PowerDesigner中转换物理模型时的命名转换 最近在使用PowerDesigner建模数据库,在使用中积累了一些遇到的问题和解决办法,记录下来,希望对遇到同样问题的朋友有所帮助. 早 期 ...
- C语言中以文本方式读写文件时换行符转换的注意事项
我们知道在UNIX下是没有回车符(\r)的,只有换行符(\n),而C语言诞生于UNIX(Linux即面向开源的UNIX,Mac OS也是UNIX发展而来的,而Windows是从MS-DOS发展而来,与 ...
- Swift3 根据秒数获取视频时长(转换成00:00:00时间格式)以及将时长转换成秒
直接代码了: /// 秒转换成00:00:00格式 /// /// - Parameter secounds: <#secounds description#> /// - Returns ...
- Angular js 双向绑定时字符串的转换成 数字类型的问题
问题: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <scrip ...
- VC2010编译时提示:转换到 COFF 期间失败: 文件无效或损坏
有时候新安装好VS2010后编译时就提示上述错误,罗列一下从网上查找到的几种解决方案: 方案1: 点击“项目”-->“属性”--> “清单工具”, 然后选择"输入和输出’--&g ...
- 使用BeanUtils封装数据时数据类型的转换
//获得表单数据 Map<String, String[]> properties = request.getParameterMap(); User user = new User(); ...
- .Net Core2.2 使用 AutoMapper进行实体转换
一.遇到的问题 在. Core Api 的编写中,我们经常会对一些功能点进行新增编辑操作,同时我们有时也会进行查询,但是我们查询的表的数据与我们返回的数据相差甚大,这是我们有需要自己手动进行类型的转换 ...
随机推荐
- [十二省联考2019]异或粽子 (可持久化01tire 堆)
/* 查询异或最大值的方法是前缀和一下, 在01trie上二分 那么我们可以对于n个位置每个地方先求出最大的数, 然后把n个信息扔到堆里, 当我们拿出某个位置的信息时, 将他去除当前最大后最大的信息插 ...
- Spring之jdbcTemplate:查询的三种方式(单个值、单个对象、对象集合)
JdbcTemplateDemo2.java package helloworld.jdbcTemplate; import org.springframework.jdbc.core.JdbcTem ...
- linux下用命令修改文件内容
修改test_modify.sh中的LICENSE_INFO test_modify.sh #!/bin/bash licenseInfo=LICENSE_INFO licenseProduct=LI ...
- 编码,基本数据类型,str索引和切片,for循环
1. 编码 1. 最早的计算机编码是ASCII. 美国人创建的. 包含了英文字母(大写字母, 小写字母). 数字, 标点等特殊字符!@#$% 128个码位 2**7 在此基础上加了一位 2**8 8位 ...
- MySQL函数大全及用法示例
1.字符串函数ascii(str) 返回字符串str的第一个字符的ascii值(str是空串时返回0) mysql> select ascii('2'); -> 50 mysq ...
- [Android]Animation 动画介绍和实现
Animation动画效果来实现菜单的显示和隐藏,本文就来介绍下吧. 1.Animation 动画类型 Android的animation由四种类型组成: XML中 alph 渐变透明度动画效果 sc ...
- REST api文档管理工具
问题: 不同软件/程序在网络中互相传递信息不统一. 交互不便. REST API 作用: RESTful API就是一套协议,用来规范多种形式的前端和同一个后台的交互方式. 原理: 组成/流程/规范: ...
- Flex 画图
<?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="h ...
- git 简单的操作命令
1, 克隆已存在项目 => git clone url 2, 拉取代码 => git pull 3, 配置账号密码 git config --global user.email &quo ...
- dubbo超时优先级设置
调用超时配置的优先级 可以在多个配置项设置超时,由上至下覆盖(即上面的优先),示例如下: # 其它的参数(retries.loadbalance.actives等)的覆盖策略也一样. 提供者端特定方法 ...