AutoMapper - Custom Type Converters

Another scenario where AutoMapper cannot do default mapping is when the types of the properties in both source and destination classes are different. Even though the names are same, there is no way AutoMapper can proceed in cases such as from String to Int32 or DateTime. If try to do mapping then AutoMapper will throw exception at the time of configuration or at the time of mapping itself.

This problem can be solved using the Custom Type Converters available in AutoMapper. We can create custom type converters by extending the ITypeConverter interface and provide the logic needed for converting the source to the destination

In this example, the type of DateOfBirth property is different in both source and destination classes. So if try to do the mapping without any converters it will throw an excetion like the one given 

Run-time exception (line 48): Missing type map configuration or unsupported mapping.

Mapping types:
String -> DateTime
System.String -> System.DateTime

Destination path:

Source value:

So to avoid this kind of exceptions, you need to create a type for the unsupported mapping. For that we will create a new class by inheriting the ITypeConverter interface and will write the conversion logic inside the Convert method as shown below.

public class DateTimeConverterForString : ITypeConverter<string, DateTime>
	public DateTime Convert(ResolutionContext context)
		return System.Convert.ToDateTime(context.SourceValue);

No Comments

Add a Comment