Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I map between two enums using Automapper?

Tags:

c#

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?

like image 892
Jeffrey Lott Avatar asked Jun 29 '12 16:06

Jeffrey Lott


People also ask

Can AutoMapper map enums?

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 to list a map?

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.

Does AutoMapper map private fields?

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.

How do you implement AutoMapper?

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.


1 Answers

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;     } }); 
like image 107
Thorsten Hüglin Avatar answered Oct 06 '22 07:10

Thorsten Hüglin