Map to a Primitive Type from a Complex Type Using AutoMapper

Map to a Primitive Type from a Complex Type Using AutoMapper

Using AutoMapper, I created a mapping for an object with many complex properties, one of which I wanted to map to a primitive type. Here’s how I configured the map from the child property to the primitive type:

CreateMap<ComplexType, int>()
    .ForMember(dest => dest, opt => opt.MapFrom(src => src.Id));

This looks like your standard map configuration: take the Id from the complex property and map it to an int. However, when attempting to run the application I received an AutoMapperConfigurationException:

Custom configuration for members is only supported for top-level individual members on a type.

The stack trace pointed to the CreateMap<ComplexType, int> configuration above. This isn’t a one-to-one mapping, I’m trying to reduce a complex object into a primitive, which AutoMapper requires some help from us to understand. For this, we’ll need to use a custom type converter.

 

Using Custom Type Converter to Map to a Primitive Type

The custom type converter allows you to take full responsibility for defining how one type maps to another. An example of this is mapping a string that looks like an int to an int.

You can create a full-fledged custom type converter by implementing the ITypeConverter<TSource, TDestination> interface, but I used the Func<TSource, TDestination> overload like so:

CreateMap<ComplexType, int>()
    .ConvertUsing(src => src.Id);

With the ConvertUsing extension in place, the mapper configuration no longer throws an exception.

I'd love to hear your thoughts