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?
The built-in enum mapper is not configurable, it can only be replaced. Alternatively, AutoMapper supports convention based mapping of enum values in a separate package AutoMapper.
How do I use AutoMapper? First, you need both a source and destination type to work with. The destination type's design can be influenced by the layer in which it lives, but AutoMapper works best as long as the names of the members match up to the source type's members.
AutoMapper will map property with private setter with no problem. If you want to force encapsulation, you need to use IgnoreAllPropertiesWithAnInaccessibleSetter. With this option, all private properties (and other inaccessible) will be ignored.
Open startup. cs class file, add “services. AddAutoMapper(typeof(Startup))” in configure services method. Now the AutoMapper Package was installed and configured in our project.
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; } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With