When using AutoMapper, it may be that we’re using types which map easily to one another, for example if the objects being mapped have the same type for a property or the type can be converted using the standard type convertes, but what happens when things get a little more complex?
Suppose we have a type, such as
public class NameType { public string Name { get; set; }
and we want to map between a string and the NameType, for example
var nameType = Mapper.Map<string, NameType>("Hello World");
As you might have suspected, this will fail as AutoMapper has no way of understanding how to convert between a string and a NameType.
You’ll see an error like this
Missing type map configuration or unsupported mapping.
Mapping types:
String -> NameType
System.String -> AutoMapperTests.Tests.NameType
Destination path:
NameType
Source value:
Hello World
What we need to do is give AutoMapper a helping hand. One way is to supply a Func to handle the conversion, such as
Mapper.CreateMap<string, NameType>(). ConvertUsing(v => new NameType { Name = v });
alternatively we can supply an ITypeConvert implementation, such as
public class NameConverter : ITypeConverter<string, NameType> { public NameType Convert(ResolutionContext context) { return new NameType {Name = (string) context.SourceValue}; } }
and use in like this
Mapper.CreateMap<string, NameType>(). ConvertUsing(new NameConverter());