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()));
Alternatively, AutoMapper supports convention based mapping of enum values in a separate package AutoMapper.
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.
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.
Use a custom type converter that tells Automapper how enums should be converted to strings:
Mapper.CreateMap<Enum, String>().ConvertUsing(e => e.ToString().ToLower());
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