简体   繁体   English

AutoMapper可以在值类型(枚举)和引用类型之间进行映射吗? (串)

[英]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: 奇怪的问题 - 我正在尝试使用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. 不要担心我使用.ToString() ,实际上我在枚举本身上使用了一个扩展方法( .ToDescription() ),但为了这个问题我一直保持简单。

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. 我看不出为什么我的AutoMapper配置没有。

Can AutoMapper handle this, am i doing something wrong, or is this a bug with AutoMapper? AutoMapper可以处理这个,我做错了什么,或者这是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. 同一行上的错误相同。 :( :(

For mapping between two types where you're taking control of the entire mapping, use ConvertUsing: 要在您控制整个映射的两种类型之间进行映射,请使用ConvertUsing:

Mapper.CreateMap<MyEnum, string>().ConvertUsing(src => src.ToString());

All the other methods assume you're mapping to individual members on the destination type. 所有其他方法都假定您映射到目标类型上的各个成员。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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