Weird problem - i'm trying to map between an enum and a string, using AutoMapper:
Mapper.CreateMap<MyEnum, string>() .ForMember(dest => dest, opt => opt.MapFrom(src => src.ToString()));
Don't worry that im using .ToString()
, in reality i'm using an extension method on the enum itself (.ToDescription()
), but i've kept it simple for the sake of the question.
The above throws an object reference error, when im doing simply setting up the mapping.
Considering this works:
string enumString = MyEnum.MyEnumType.ToString();
I can't see why my AutoMapper configuration does not.
Can AutoMapper handle this, am i doing something wrong, or is this a bug with AutoMapper?
Any ideas?
EDIT
I also tried using a custom resolver:
Mapper.CreateMap<MyEnum, string>() .ForMember(dest => dest, opt => opt.ResolveUsing<MyEnumResolver>()); public class MyEnumResolver: ValueResolver<MyEnum,string> { protected override string ResolveCore(MyEnum source) { return source.ToString(); } }
Same error on same line. :(
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.
If you have to do complex mapping behavior, it might be better to avoid using AutoMapper for that scenario. Reverse mapping can get very complicated very quickly, and unless it's very simple, you can have business logic showing up in mapping configuration.
AutoMapper is a popular object-to-object mapping library that can be used to map objects belonging to dissimilar types. As an example, you might need to map the DTOs (Data Transfer Objects) in your application to the model objects.
AutoMapper is a great tool when used for simple conversions. When you start using more complex conversions, AutoMapper can be invaluable. For very simple conversions you could of course write your own conversion method, but why write something that somebody already has written?
For mapping between two types where you're taking control of the entire mapping, use ConvertUsing:
Mapper.CreateMap<MyEnum, string>().ConvertUsing(src => src.ToString());
All the other methods assume you're mapping to individual members on the destination type.
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