Custom type converterssometimes, you need to take complete control over the conversion of one Type to another. This was 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{ publicstringgetset;} Public string Get Set ; } Public string Get Set ; }}
But you would like to map it to:
Public class destination{ publicintgetset;} Public Get Set ; } Public Get Set ; }}
If we were to try and map these-types As-is, AutoMapper would throw an exception (at map time and Configuration-checki ng time), as AutoMapper does not know on any mapping from string to int, DateTime or Type. To create the maps for these types, we must supply a custom type converter, and we had three ways of doing so:
void Convertusing (Func<tsource, tdestination> mappingfunction); void Convertusing (Itypeconverter<tsource, tdestination> Converter); void 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 would instan Tiate at run time. The mapping configuration for we above source/destination types then becomes:
[Test] Public voidExample () {Mapper.createmap<string,int>(). Convertusing (Convert.ToInt32); Mapper.createmap<string, Datetime> (). Convertusing (NewDatetimetypeconverter ()); Mapper.createmap<string, Type> (). Convertusing<typetypeconverter>(); Mapper.createmap<source, destination>(); Mapper.assertconfigurationisvalid (); varSource =NewSource {Value1="5", Value2="01/01/2000", Value3="automappersamples.globaltypeconverters.globaltypeconverters+destination" }; Destination result= Mapper.map<source, destination>(source); Result. Value3.shouldequal (typeof(Destination));} Public classdatetimetypeconverter:itypeconverter<string, datetime>{ PublicDateTime Convert (stringsource) { returnSystem.Convert.ToDateTime (source); }} Public classtypetypeconverter:itypeconverter<string, type>{ PublicType Convert (stringsource) {Type type=assembly.getexecutingassembly (). GetType (source); returntype; }}
User-defined conversions in AutoMapper