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

RPM1984 picture RPM1984 · Apr 12, 2011 · Viewed 22.6k times · Source

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

Answer

Jimmy Bogard picture Jimmy Bogard · Apr 12, 2011

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.