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:

public class Source
{
public string Value1 { get; set; }
public string Value2 { get; set; }
public string Value3 { get; set; }
}

But you would like to map it to:

public class Destination
{
public int Value1 { get; set; }
public DateTime Value2 { get; set; }
public Type Value3 { get; set; }
}

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:

void ConvertUsing(Func<TSource, TDestination> mappingFunction);
void ConvertUsing(ITypeConverter<TSource, TDestination> converter);
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>:

public interface ITypeConverter<TSource, TDestination>
{
TDestination Convert(TSource source);
}

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:

[Test]
public void Example()
{
Mapper.CreateMap<string, int>().ConvertUsing(Convert.ToInt32);
Mapper.CreateMap<string, DateTime>().ConvertUsing(new DateTimeTypeConverter());
Mapper.CreateMap<string, Type>().ConvertUsing<TypeTypeConverter>();
Mapper.CreateMap<Source, Destination>();
Mapper.AssertConfigurationIsValid(); var source = new Source
{
Value1 = "",
Value2 = "01/01/2000",
Value3 = "AutoMapperSamples.GlobalTypeConverters.GlobalTypeConverters+Destination"
}; Destination result = Mapper.Map<Source, Destination>(source);
result.Value3.ShouldEqual(typeof (Destination));
} public class DateTimeTypeConverter : ITypeConverter<string, DateTime>
{
public DateTime Convert(string source)
{
return System.Convert.ToDateTime(source);
}
} public class TypeTypeConverter : ITypeConverter<string, Type>
{
public Type Convert(string source)
{
Type type = Assembly.GetExecutingAssembly().GetType(source);
return type;
}
}

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. MT【212】合作共赢

    一次会议有1990位数学家参加,每人至少有过1327位合作者,求证:可以找到4位数学家,他们中每一个都合作过. 解答:记与$v_i$合作过的数学家构成集合$A_i(i=1,2,\cdots,1990) ...

  2. MT【211】保序同构

    设$S,T$是$R$的两个非空子集,如果存在一个从$S$到$T$的函数$y=f(x)$满足:$1)T=\{f(x)|x\in S\};$2)对任意$x_1,x_2\in S$,当$x_1<x_2 ...

  3. 【刷题】LOJ 2863 「IOI2018」组合动作

    题目描述 你在玩一个动作游戏.游戏控制器有 \(4\) 个按键,A.B.X 和 Y.在游戏中,你用组合动作来赚金币.你可以依次按这些按键来完成一个组合动作. 这个游戏有一个隐藏的按键序列,可以表示为由 ...

  4. php laravel 多条件筛选

    效果如图,点击的条件出现在已选择的地方,点击已选择的条件可以删除当前点击的条件 语言是php 框架是laravel. 一.html <div class="doctor-conditi ...

  5. 自学Zabbix9.1 Network Discovery 网络发现原理

    点击返回:自学Zabbix之路 点击返回:自学Zabbix4.0之路 点击返回:自学zabbix集锦 自学Zabbix9.1 Network Discovery 网络发现原理 1. 网络发现简介 网络 ...

  6. 【BZOJ3668】【NOI2014】起床困难综合症(贪心)

    [NOI2014]起床困难综合症(贪心) 题面 Description 21 世纪,许多人得了一种奇怪的病:起床困难综合症,其临床表现为:起床难,起床后精神不佳.作为一名青春阳光好少年,atm 一直坚 ...

  7. 洛谷 P2059 [JLOI2013]卡牌游戏 解题报告

    P2059 [JLOI2013]卡牌游戏 题意 有\(n\)个人玩约瑟夫游戏,有\(m\)张卡,每张卡上有一个正整数,每次庄家有放回的抽一张卡,干掉从庄家起顺时针的第\(k\)个人(计算庄家),干掉的 ...

  8. Hadoop HDFS命令

    hadoop fs -mkdir  创建HDFS目录 # hadoop fs -mkdir /data Hadoop fs -ls  列出HDFS目录 # hadoop fs -ls /data ha ...

  9. [FJOI2017]矩阵填数——容斥

    参考:题解 P3813 [[FJOI2017]矩阵填数] 题目大意: 给定一个 h∗w 的矩阵,矩阵的行编号从上到下依次为 1...h ,列编号从左到右依次 1...w . 在这个矩阵中你需要在每个格 ...

  10. python-requests-proxies判断学习

    # coding:utf8 import requests def prox(): url = 'http://115.159.33.177/images/ip.php' ip_list = [ 'h ...