How can I map between two enums using Automapper?
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?
Solution 1:
Alternatively to writing custom converters, just use ConvertUsing()
Mapper.CreateMap<EnumSrc, EnumDst>().ConvertUsing((value, destination) =>
{
switch(value)
{
case EnumSrc.Option1:
return EnumDst.Choice1;
case EnumSrc.Option2:
return EnumDst.Choice2;
case EnumSrc.Option3:
return EnumDst.Choice3;
default:
return EnumDst.None;
}
});
Solution 2:
You don't need to do CreateMap for enum types. Just get rid of the CreateMap call and it should work, as long as the names and/or values match up between enum types.
Solution 3:
My Automapper works this way:
If I create a map: Automapper will match enums by value, even if name match perfectly.
If I do not create a map: Automapper will match enums by name.
Solution 4:
The Simplest Way I found that work for me is as below:
My Enum is a nested in another class so I Use ForMember method and MapFrom as below:
Mapper.CreateMap<ProblematicCustomer, ProblematicCustomerViewModel>()
.ForMember(m=> m.ProblemType, opt=> opt.MapFrom(x=> (ProblemTypeViewModel)(int)x.ProblemType))
.ForMember(m=> m.JudgmentType, opt=> opt.MapFrom(x=> (JudgmentTypeViewModel)(int)x.JudgmentType));
The ProblemType and JudgmentType are Enums. And their related View Models are ProblemTypeViewModel and JudgmentTypeViewModel with same members as their related Models.
Although I don't test, But I think below line should work for you:
Mapper.CreateMap<Contract_1_1_0.ValidationResultType, Common.ValidationResultType>()
.ForMember(m=> m, opt => opt.MapFrom(x=> (Common.ValidationResultType)(int)x);
Hope it Help.
Solution 5:
The other answers here didn't work for me.
You need to create a class that implements:
ITypeConvertor<SourceType ,DestinationType>
So as an example
Mapper.CreateMap<EnumType1.VatLevel, EnumType2.VatRateLevel>()
.ConvertUsing(new VatLevelConvertor());
And the class:
internal class VatLevelConvertor : ITypeConverter<EnumType1.VatLevel, EnumType2.VatRateLevel>
{
public EnumType2.VatRateLevel Convert(ResolutionContext context)
{
EnumType1.VatLevel value = (EnumType1.VatLevel)context.SourceValue;
switch (value)
{
case EnumType1.VatLevel.Standard:
return EnumType2.VatRateLevel.Normal;
case EnumType1.VatLevel.Reduced:
return EnumType2.VatRateLevel.Lower;
case EnumType1.VatLevel.SuperReduced:
return EnumType2.VatRateLevel.Other;
default:
return EnumType2.VatRateLevel.Other;
}
}
}