Custom Type Converters

Sometimes, you need to take complete control over the conversion of one type to another. This is typically when one type looks nothing like the other, a conversion function already exists, and you would like to go from a "looser" type to a stronger type, such as a source type of string to a destination type of Int32.

For example, suppose we have a source type of:

  1. public class Source
  2. {
  3. public string Value1 { get; set; }
  4. public string Value2 { get; set; }
  5. public string Value3 { get; set; }
  6. }

But you would like to map it to:

  1. public class Destination
  2. {
  3. public int Value1 { get; set; }
  4. public DateTime Value2 { get; set; }
  5. public Type Value3 { get; set; }
  6. }

If we were to try and map these two types as-is, AutoMapper would throw an exception (at map time and configuration-checking time), as AutoMapper does not know about any mapping from string to int, DateTime or Type. To create maps for these types, we must supply a custom type converter, and we have three ways of doing so:

  1. void ConvertUsing(Func<TSource, TDestination> mappingFunction);
  2. void ConvertUsing(ITypeConverter<TSource, TDestination> converter);
  3. void ConvertUsing<TTypeConverter>() where TTypeConverter : ITypeConverter<TSource, TDestination>;

The first option is simply any function that takes a source and returns a destination. This works for simple cases, but becomes unwieldy for larger ones. In more difficult cases, we can create a custom ITypeConverter<TSource, TDestination>:

  1. public interface ITypeConverter<TSource, TDestination>
  2. {
  3. TDestination Convert(TSource source);
  4. }

And supply AutoMapper with either an instance of a custom type converter, or simply the type, which AutoMapper will instantiate at run time. The mapping configuration for our above source/destination types then becomes:

  1. [Test]
  2. public void Example()
  3. {
  4. Mapper.CreateMap<string, int>().ConvertUsing(Convert.ToInt32);
  5. Mapper.CreateMap<string, DateTime>().ConvertUsing(new DateTimeTypeConverter());
  6. Mapper.CreateMap<string, Type>().ConvertUsing<TypeTypeConverter>();
  7. Mapper.CreateMap<Source, Destination>();
  8. Mapper.AssertConfigurationIsValid();
  9.  
  10. var source = new Source
  11. {
  12. Value1 = "",
  13. Value2 = "01/01/2000",
  14. Value3 = "AutoMapperSamples.GlobalTypeConverters.GlobalTypeConverters+Destination"
  15. };
  16.  
  17. Destination result = Mapper.Map<Source, Destination>(source);
  18. result.Value3.ShouldEqual(typeof (Destination));
  19. }
  20.  
  21. public class DateTimeTypeConverter : ITypeConverter<string, DateTime>
  22. {
  23. public DateTime Convert(string source)
  24. {
  25. return System.Convert.ToDateTime(source);
  26. }
  27. }
  28.  
  29. public class TypeTypeConverter : ITypeConverter<string, Type>
  30. {
  31. public Type Convert(string source)
  32. {
  33. Type type = Assembly.GetExecutingAssembly().GetType(source);
  34. return type;
  35. }
  36. }

AutoMapper中用户自定义转换的更多相关文章

  1. SQL Server中行列转换 Pivot UnPivot

    SQL Server中行列转换 Pivot UnPivot PIVOT用于将列值旋转为列名(即行转列),在SQL Server 2000可以用聚合函数配合CASE语句实现 PIVOT的一般语法是:PI ...

  2. awk中分隔符转换

    awk中分隔符转换的问题(转) 在awk中明明用OFS重新设置了分隔符,为什么在输出的时候还是原样输出呢! 他是这么写的:    echo 1,2,3,4 | awk 'BEGIN{FS=" ...

  3. kettle删除资源库中的转换或者作业

    在资源库中新建转换,作业都很简单,那么加入现在不需要其中某个转换或者作业该怎么办呢? 下图是已经存在的转换跟作业 现在需要删除aa这个转换 操作步骤如下: 1.工具----资源库----探索资源库 出 ...

  4. Java中String转换Double类型 Java小数点后留两位

    Java中String转换Double类型 double num1 = 0.0; String qq = "19.987"; num1 = Double.valueOf(qq.to ...

  5. VSTO中Word转换Range为Image的方法

    VSTO中Word转换Range为Image的方法 前言 VSTO是一套用于创建自定义Office应用程序的Visual Studio工具包,通过Interop提供的增强Office对象,可以对Wor ...

  6. js中时间戳转换成时间格式

    js中时间戳转换成时间格式, // 时间戳转换成时间格式 var formatDate = function(date){ date = new Date(date); var y=date.getF ...

  7. QT国际化(中英转换)

    转载:https://blog.csdn.net/u012528526/article/details/54707233 QT国际化(中英转换) 我们都知道在安卓中,想做国际化很简单,只需要建立对应的 ...

  8. AS3中String转换成Boolean

    AS3中, 对布尔值的转换, 规定所有的非空字符串都是true. 下面都不行: var f:Boolean = new Boolean(str); var f:Boolean = str as Boo ...

  9. SQL中DateTime转换成Varchar样式

    SQL中DateTime转换成Varchar样式语句及查询结果:Select CONVERT(varchar(100), GETDATE(), 0): 05 16 2006 10:57AMSelect ...

随机推荐

  1. 洛谷P3628 [APIO2010]特别行动队(动态规划,斜率优化,单调队列)

    洛谷题目传送门 安利蒟蒻斜率优化总结 由于人是每次都是连续一段一段地选,所以考虑直接对\(x\)记前缀和,设现在的\(x_i=\)原来的\(\sum\limits_{j=1}^ix_i\). 设\(f ...

  2. Spring事务说明与自实现

    要使用Springboot的事务其实非常简单,在启动类上添加@EnableTransactionManagement,在Service的类或者方法上使用@Transactional就可以了. 事务本身 ...

  3. 【BZOJ4591】[SHOI2015]超能粒子炮·改 (卢卡斯定理)

    [BZOJ4591][SHOI2015]超能粒子炮·改 (卢卡斯定理) 题面 BZOJ 洛谷 题解 感天动地!终于不是拓展卢卡斯了!我看到了一个模数,它是质数!!! 看着这个东西就感觉可以递归处理. ...

  4. Logstash 解析Json字符串,删除json嵌套字段

    一.场景:此文以一个简单的json字符串文件为例,描述如何用logstash解析嵌套的json,并删除其中的某些字段 我们在linux中test.json的内容如下: {"timestamp ...

  5. wildfly jobss 同时连接多个数据源 datasource xa-datasource

    由于需要从一个远程机器取数据.处理后保存到本地数据库处理.用 wildfly datasource 会报: [com.arjuna.ats.arjuna] (default task-6) ARJUN ...

  6. Pentaho data integration(kettle) 在Mac上启动不了

    环境 MacOS Mojave (10.14.1) Pentaho Data Integration 8.2 Java 8 现象 从官方下载下来最新的安装包,解压之后,双击Data Integrati ...

  7. 第2课:什么是SQL注入

    SQL注入:利用现有应用程序,将(恶意)的SQL命令注入到后台数据库引擎执行的能力,这是SQL注入的标准释义. 随着B/S模式被广泛的应用,用这种模式编写应用程序的程序员也越来越多,但由于开发人员的水 ...

  8. grafana worldPing插件

    worldPing插件安装 官网介绍:https://grafana.com/plugins/raintank-worldping-app/installation 插件下砸地址:https://gr ...

  9. CPU密集型和I/O密集型区别

    CPU密集型 一些进程绝大多数时间在计算上,称为计算密集型(CPU密集型)computer-bound.一些大量循环的代码(例如:图片处理.视频编码.人工智能等)就是CPU密集型. I/O密集型 有一 ...

  10. python---定义一个session类(无错)

    import tornado.web #放在内存 redis 文件 数据库 container={} #定义一个session类 class Session: def __init__(self,ha ...