How can I map between two enums using Automapper?

Jeffrey Lott picture Jeffrey Lott · Jun 29, 2012 · Viewed 43.3k times · Source

I have a public facing interface that I'm trying to map two different enumerations to each other. I tried to use the following code:

Mapper.CreateMap<Contract_1_1_0.ValidationResultType, Common.ValidationResultType>();

When that didn't work, I tried:

Mapper.CreateMap<Contract_1_1_0.ValidationResultType, Common.ValidationResultType>().ConvertUsing(x => (Common.ValidationResultType)((int)x));

But that doesn't seem to work either. Is there anyway to get automapper to handle this scenario?

Answer

Thorsten H&#252;glin picture Thorsten Hüglin · Jul 8, 2015

Alternatively to writing custom converters, just use ConvertUsing()

Mapper.CreateMap<EnumSrc, EnumDst>().ConvertUsing(value => 
{
    switch(value)
    {
        case EnumSrc.Option1:
            return EnumDst.Choice1;
        case EnumSrc.Option2:
            return EnumDst.Choice2;
        case EnumSrc.Option3:
            return EnumDst.Choice3;
        default:
            return EnumDst.None;
    }
});