Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
828 views
in Technique[技术] by (71.8m points)

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

question from:https://stackoverflow.com/questions/5631377/can-automapper-map-between-a-value-type-enum-and-reference-type-string

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...