简体   繁体   中英

Generic Enum to Lowercased String Mapping Using 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()));

使用自定义类型转换器告诉Automapper如何将枚举转换为字符串:

Mapper.CreateMap<Enum, String>().ConvertUsing(e => e.ToString().ToLower());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM