Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic Enum to Lowercased String Mapping Using AutoMapper

Tags:

c#

automapper

I currently map all of my differnt enum value types to a lower cased string value. I have multiple maps that contain duplicate logic in them. Is there away to take the following AutoMapper code and tell it to always convert enums to lowercased string values?

Mapper.CreateMap<Class1, OutClass1>()
   .ForMember(dest => dest.Enum1String, opt => opt.MapFrom(src => src.Enum1.ToString().ToLower()))
   .ForMember(dest => dest.Enum2String, opt => opt.MapFrom(src => src.Enum2.ToString().ToLower()));

Mapper.CreateMap<Class2, OutClass2>()
   .ForMember(dest => dest.Enum2String, opt => opt.MapFrom(src => src.Enum2.ToString().ToLower()));
like image 627
Phil Avatar asked Jul 25 '12 18:07

Phil


People also ask

Can AutoMapper map enums?

Alternatively, AutoMapper supports convention based mapping of enum values in a separate package AutoMapper.

What is AutoMapper in C# with example?

AutoMapper in C# is a library used to map data from one object to another. It acts as a mapper between two objects and transforms one object type into another. It converts the input object of one type to the output object of another type until the latter type follows or maintains the conventions of AutoMapper.

What is reverse map in AutoMapper?

The Automapper Reverse Mapping is nothing but the two-way mapping which is also called as bidirectional mapping. As of now, the mapping we discussed are one directional means if we have two types let's say Type A and Type B, then we Map Type A with Type B.


1 Answers

Use a custom type converter that tells Automapper how enums should be converted to strings:

Mapper.CreateMap<Enum, String>().ConvertUsing(e => e.ToString().ToLower());
like image 127
PatrickSteele Avatar answered Oct 31 '22 09:10

PatrickSteele