自动映射器枚举描述属性 [英] Automapper Enum Description Attribute
问题描述
我在从Enum Description属性进行映射时遇到困难.我一直在寻找一个有用的例子,运气很少.我知道还有一些其他示例,但我仍在为这种特殊情况而苦苦挣扎.
I'm having difficulties mapping from an Enum Description Attribute. I've been looking all over for a useful example with very little luck. I know there are some other examples out there but I'm still struggling with this particular scenario.
这是我的枚举:
public enum ResolveCodeEnum
{
[Description("Resolved - Workaround")]
ResolvedWorkaround = 1,
[Description("Resolved - Permanently")]
ResolvedPermanently = 2,
[Description("Resolved - Unknown")]
ResolvedUnkown = 3,
[Description("Cannot Reproduce")]
CannotReproduce = 4,
[Description("Invalid")]
Invalid = 5,
[Description("Cancelled")]
Cancelled = 6
}
这是我的枚举助手类:
public class EnumHelper
{
public static string GetEnumDescription(Enum value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes =
(DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes != null && attributes.Length > 0)
return attributes[0].Description;
else
return value.ToString();
}
}
我的目标是通过Enum Description属性将源映射到目标
My goal is to map source to destination via Enum Description Attribute
这是到目前为止我的映射配置:
Here is what I have so far in my mapping configuration:
Mapper.CreateMap<Result, Incident>()
.ForMember(dest => dest.Status,
opts => opts.MapFrom(src => src.state));
这里是Result类的缩写:
Here is the abbreviated Result class:
public class Result
{
public string sys_id { get; set; }
public string state { get; set; }
}
这是缩写的事件类:
public class Incident
{
public string Id{ get; set; }
public string Status{ get; set; }
}
注意:Result类的state属性是一个字符串
Note: the state property of the Result class is a string
例如:
我的目标是获得
Incident.Status = "Resolved - Workaround"
来自
Result.state = "1"
我一直在努力与EnumHelper类一起使用的自动映射器语法
I've been struggle with the automapper syntax to use with my EnumHelper class
如果有人可以帮助我,将不胜感激:)
If anybody can help me out on this, it would be greatly appreciated :)
推荐答案
执行此操作的两种方法:
Two ways to do this:
-
与
ResolveUsing
内联:
Mapper.CreateMap<Result, Incident>()
.ForMember(
dest => dest.Status,
opt => opt.ResolveUsing(src =>
{
var value = (ResolveCodeEnum)Enum.Parse(
typeof(ResolveCodeEnum), src.state);
return EnumHelper.GetEnumDescription(value);
}));
带有自定义的ValueResolver
:
public class EnumValueResolver : ValueResolver<Result, string>
{
protected override string ResolveCore(Result src)
{
var value = (ResolveCodeEnum)Enum.Parse(typeof(ResolveCodeEnum), src.state);
return EnumHelper.GetEnumDescription(value);
}
}
用法:
Mapper.CreateMap<Result, Incident>()
.ForMember(
dest => dest.Status,
opt => opt.ResolveUsing<EnumValueResolver>());
我建议#2,因为它更干净.
I'd recommend #2 since it's much cleaner.
这篇关于自动映射器枚举描述属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!