AutoMapper 可以在值类型(枚举)和引用类型之间映射吗? (细绳)
奇怪的问题 - 我正在尝试使用 AutoMapper 在 enum 和 string 之间进行映射:
Mapper.CreateMap<MyEnum, string>()
.ForMember(dest => dest, opt => opt.MapFrom(src => src.ToString()));
不用担心我使用 .ToString()
,实际上我在枚举本身上使用了扩展方法(.ToDescription()
),但为了解决问题,我保持了简单。
当我简单地设置映射时,上面会抛出一个对象引用错误。
考虑到这是有效的:
string enumString = MyEnum.MyEnumType.ToString();
我不明白为什么我的 AutoMapper 配置不起作用。
AutoMapper 可以处理这个问题吗?我做错了什么吗?或者这是 AutoMapper 的一个错误吗?
有什么想法吗?
编辑
我还尝试使用自定义解析器:
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();
}
}
同一行出现同样的错误。 :(
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. :(
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于要控制整个映射的两种类型之间的映射,请使用 ConvertUsing:
所有其他方法都假设您要映射到目标类型上的各个成员。
For mapping between two types where you're taking control of the entire mapping, use ConvertUsing:
All the other methods assume you're mapping to individual members on the destination type.