Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can AutoMapper Map Between a Value Type (Enum) and Reference Type? (string)

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. :(

like image 756
RPM1984 Avatar asked Apr 12 '11 06:04

RPM1984


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.

When should you not use 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.

What is AutoMapper used for?

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.

Is it good to use AutoMapper?

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?


1 Answers

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.

like image 57
Jimmy Bogard Avatar answered Sep 25 '22 12:09

Jimmy Bogard