AutoMapper(三)
自定义类型转换
有时,需要完全控制一个类型到另一个类型的转换。一个类型一点都不像另一个类型,而且转换函数已经存在了,在这种情况下,你想要从一个“宽松”的类型转换成一个更强壮的类型,例如一个string的源类型到一个int32的目标类型。
这里有两个类Source和Destination,要把前者映射到后者,代码如下:
public class Source
{
public string Value1 { get; set; }
public string Value2 { get; set; }
public string Value3 { get; set; }
}
public class Destination
{
public int Value1 { get; set; }
public DateTime Value2 { get; set; }
public Type Value3 { get; set; }
}
截至发稿前,官方文档这样描述的“因为AutoMapper不清楚从string到int,Datetime或Type的映射,如果要尝试映射的话,AutoMapper就会抛出异常(在映射时和配置检查时)”。为了创建 这些类型的映射,我们必须提供自定义的类型转换器,我们有三种方法这样做:
void ConvertUsing(Func<TSource, TDestination> mappingFunction);
void ConvertUsing(ITypeConverter<TSource, TDestination> converter);
void ConvertUsing<TTypeConverter>() where TTypeConverter : ITypeConverter<TSource, TDestination>;
但是,我先不实现自定义的类型转换器试一下:
namespace ThirdAutoMapper
{
class Program
{
static void Main(string[] args)
{
Mapper.CreateMap<Source, Destination>();
var source = new Source
{
Value1 = "",
Value2 = "05/11/2015",
Value3 = "ThirdAutoMapper.Source"
}; var destination = Mapper.Map<Destination>(source);
Console.WriteLine("destination.Value1={0}", destination.Value1);
Console.WriteLine("destination.Value2={0}", destination.Value2);
Console.Read();
}
}
}
出现如下错误,但从错误看来,只有从string到Type类型映射时,出现了错误,其他两种类型呢?

现在我们将源类型和目标类型的第三个属性Value3注释掉,同时注释掉参与映射前的源类型对象的Value3属性,再来试一下。

果然,发现映射成功。也就说说最新版的AutoMapper默认可以将string类型映射为int和DateTime类型了。但是string还是没办法映射为Type类型。
对于以上AutoMapper的API给出的三种转换方法,第一个选择只是输入一个源返回一个目标的函数,这对于简单场合是有效的,但是对于更大的案例会变得难以处理。在更复杂的情况下,我们可以一个自定义的类型转换器,通过实现ITypeConverter<TSource, TDestination>接口创建:
第一种方法:
public class CustomTypeConverter : ITypeConverter<Source, Destination>
{ public Destination Convert(ResolutionContext context)
{
Source src = context.SourceValue as Source;
var dest = new Destination
{
Value1 = System.Convert.ToInt32(src.Value1),
Value2 = System.Convert.ToDateTime(src.Value2),
Value3 = context.SourceType
};
return dest;
}
}
然后给AutoMapper提供一个自定义类型的转换器或者AutoMapper在运行时能实例化的简化类型。对于上面的源/目标类型的映射配置就得以实现了:
修改Main方法中的代码为:
static void Main(string[] args)
{ Mapper.CreateMap<Source, Destination>().ConvertUsing<CustomTypeConverter>();
var source = new Source
{
Value1 = "",
Value2 = "05/11/2015",
Value3 = typeof(Source).ToString()
};
var destination = Mapper.Map<Destination>(source);
Console.WriteLine("destination.Value1={0}", destination.Value1);
Console.WriteLine("destination.Value2={0}", destination.Value2);
Console.WriteLine(destination.Value3.ToString()==source.Value3);
Console.WriteLine(destination.Value3);
Console.Read();
}
测试结果如下,映射成功!

第二种方法:
每个类型分别实现ITypeConverter接口:
public class DateTimeTypeConverter:ITypeConverter<string,DateTime>
{ public DateTime Convert(ResolutionContext context)
{
return System.Convert.ToDateTime(context.SourceValue);
}
} public class TypeTypeConverter : ITypeConverter<string, Type>
{ public Type Convert(ResolutionContext context)
{
return context.SourceValue == typeof(Source).ToString() ? typeof(Source) : typeof(Destination);
}
}
static void Main(string[] args)
{
//我看网上很多这种写法,包括官方文档,但是我这样写编译错误,可能是现在的AutoMapper不支持了吧
// Mapper.CreateMap<string, int>().ConvertUsing( Convert.ToInt32); Mapper.CreateMap<string, int>().ConvertUsing((context, intNum) => Convert.ToInt32(context.SourceValue));
Mapper.CreateMap<string, DateTime>().ConvertUsing(new DateTimeTypeConverter().Convert);
Mapper.CreateMap<string, Type>().ConvertUsing<TypeTypeConverter>(); Mapper.CreateMap<Source, Destination>();
//Mapper.CreateMap<Source, Destination>().ConvertUsing<CustomTypeConverter>();
var source = new Source
{
Value1 = "",
Value2 = "05/11/2015",
Value3 = typeof(Source).ToString()
}; var destination = Mapper.Map<Destination>(source);
Console.WriteLine("destination.Value1={0}", destination.Value1);
Console.WriteLine("destination.Value2={0}", destination.Value2);
Console.WriteLine(destination.Value3.ToString()==source.Value3);
Console.WriteLine(destination.Value3);
Console.Read();
}
测试结果,同样完美通过。

AutoMapper(三)的更多相关文章
- NetCore+AutoMapper多个对象映射到一个Dto对象
目录 一. 定义源映射类和被映射类DTO二.注入AutoMapper三.配置映射四.写测试 一.定义源映射对象 为了体现AutoMapper映射特性,在SocialAttribute中的Name属性没 ...
- ABP源码分析三十一:ABP.AutoMapper
这个模块封装了Automapper,使其更易于使用. 下图描述了改模块涉及的所有类之间的关系. AutoMapAttribute,AutoMapFromAttribute和AutoMapToAttri ...
- DTO学习系列之AutoMapper(三)
本篇目录: Custom Type Converters-自定义类型转换器 Custom Value Resolvers-自定义值解析器 Null Substitution-空值替换 Containe ...
- 一步一步创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar](三)
前言 上一篇<一步一步创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar](二)>我们通过如下操作: 创建实体及工具类 创建Re ...
- 【AutoMapper官方文档】DTO与Domin Model相互转换(中)
写在前面 AutoMapper目录: [AutoMapper官方文档]DTO与Domin Model相互转换(上) [AutoMapper官方文档]DTO与Domin Model相互转换(中) [Au ...
- AutoMapper(二)
返回总目录 首先,先创建一个控制台项目,引用AutoMapper程序集,创建三个类User,UserDto,UserMappingProfile,下面的知识点的演示都以此项目为基础,代码分别如下: n ...
- 五步掌握OOM框架AutoMapper基本使用
本文版权归博客园和作者吴双本人共同所有,转载和爬虫请注明原文地址 www.cnblogs.com/tdws 写在前面 OOM顾名思义,Object-Object-Mapping实体间相互转换,Aut ...
- 使用Adminlite + ASP.NET MVC5(C#) + Entityframework + AutoFac + AutoMapper写了个api接口文档管理系统
一.演示: 接口查看:http://apidoc.docode.top/ 接口后台:http://apiadmin.docode.top/ 登录:administrator,123456 二.使用到的 ...
- AutoMapper使用手册(一)
阅读目录 1. 介绍 2. 基本使用 3. 自动分割映射(Flattening) 4. 自定义字段映射(Projection) 5. 验证配置(Configuration validation) 介绍 ...
随机推荐
- NodeJs之Path
Path模块 NodeJs提供的Path模块,使得我们可以对文件路径进行简单的操作. API var path = require('path'); var path_str = '\\Users\\ ...
- DDD 领域驱动设计-看我如何应对业务需求变化,愚蠢的应对?
写在前面 阅读目录: 具体业务场景 业务需求变化 "愚蠢"的应对 消息列表实现 消息详情页实现 消息发送.回复.销毁等实现 回到原点的一些思考 业务需求变化,领域模型变化了吗? 对 ...
- 散列表(hash table)——算法导论(13)
1. 引言 许多应用都需要动态集合结构,它至少需要支持Insert,search和delete字典操作.散列表(hash table)是实现字典操作的一种有效的数据结构. 2. 直接寻址表 在介绍散列 ...
- Matlab slice方法和包络法绘制三维立体图
前言:在地球物理勘探,流体空间分布等多种场景中,定位空间点P(x,y,x)的物理属性值Q,并绘制三维空间分布图,对我们洞察空间场景有十分重要的意义. 1. 三维立体图的基本要件: 全空间网格化 网格节 ...
- 利用XAG在RAC环境下实现GoldenGate自动Failover
概述 在RAC环境下配置OGG,要想实现RAC节点故障时,OGG能自动的failover到正常节点,要保证两点: 1. OGG的checkpoint,trail,BR文件放置在共享的集群文件系统上,R ...
- ASP.NET Core的路由[1]:注册URL模式与HttpHandler的映射关系
ASP.NET Core的路由是通过一个类型为RouterMiddleware的中间件来实现的.如果我们将最终处理HTTP请求的组件称为HttpHandler,那么RouterMiddleware中间 ...
- node中的Stream-Readable和Writeable解读
在node中,只要涉及到文件IO的场景一般都会涉及到一个类-Stream.Stream是对IO设备的抽象表示,其在JAVA中也有涉及,主要体现在四个类-InputStream.Reader.Outpu ...
- Spring注解
AccountController .java Java代码 1. /** 2. * 2010-1-23 3. */ 4. packag ...
- js闭包for循环总是只执行最后一个值得解决方法
<style> li{ list-style: none;width:40px;height: 40px;text-align:center;line-height: 40px;curso ...
- IOS之Objective-C学习 ARC下的单例模式
单例模式是我常用的一种设计模式,最常见的用途就是用来保存数据并且传递数据.这都归功于单例模式的特性,首先就让我为大家简单介绍一下单例模式的特性. 单例模式的三大特性: 1.某个类只能有一个实例: 2. ...