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. Web项目替换jar包中的文件的方法

    经常遇到这样的问题,需要修改jar包中的方法.应该如何做? 1.有些很人性化的框架jar包,比如SpringSecurity,可以修改配置文件指定一个新建的类,让类实现Jar包中的对应的接口就好了. ...

  2. Oracle Client安装报错:引用数据不可用于验证此操作系统分发的先决条件

    原因是Oracle Client 11g版本不支持最新的Win10系统. 打开Oracle Client 11g安装包目录:\client\stage\cvu 编辑该目录下的两个xml文件:oracl ...

  3. MT【191】阿波罗尼乌斯圆

    已知$f(x)=2\sqrt{(\cos x+\frac{1}{2})^2+\sin^2 x}-\sqrt{\cos^2 x+(\sin x-\frac{1}{2})^2}$,若$m\ge f(x)$ ...

  4. INSTALL_FAILED_INSUFFICIENT_STORAGE 的解决方法

    今天用真机测试,出现了下面的情况 , 网上找了好多情况 , 都感觉比较费事,没什么效果,报错依旧, [2013-08-06 16:31:04 - Flashlight] Installation er ...

  5. [NOI2017]泳池——概率DP+线性递推

    [NOI2017]泳池 实在没有思路啊~~~ luogu题解 1.差分,转化成至多k的概率减去至多k-1的概率.这样就不用记录“有没有出现k”这个信息了 2.n是1e9,感觉要递推然后利用数列的加速技 ...

  6. P1198 最大数 线段树水题

    这道题模拟一下可以过,但是我们发现线段树也可以安全水过...... 写的线段树只需要滋磁单点修改,区间求max即可 我一开始犯了一个很SB的错误:每次插入修改了t,然后疯狂爆0到怀疑人生... 而且我 ...

  7. win+R快捷启动程序

    win10: Win+R cmd:命令行程序 notepad:记事本 winword:word文档 calc:记事本 mspaint:画图 wordpad:写字板

  8. vcf文件(call variants得来的)怎么看变异是纯合还是杂合的

    如下图片所示: 对于位置为48245131的allele来说,REF为A,ALT为C 想确定变异到底是纯合还是杂合,即两条染色体是否同时发生了变异,则看GT,GT对应的数值为0/1,说明该变异为杂合: ...

  9. idea中的language level 介绍

    language level 介绍 其他 IDE 没有看到类似 language level 的设置,所以这个功能应该算是 IntelliJ IDEA 特有的,可是 IntelliJ IDEA 官网也 ...

  10. 搞定 Kubernetes 基于flannel 的集群网络

    .Docker网络模式 在讨论Kubernetes网络之前,让我们先来看一下Docker网络.Docker采用插件化的网络模式,默认提供bridge.host.none.overlay.maclan和 ...