我从Enum描述属性映射有困难。我一直在寻找一个有用的例子,但运气不好。我知道还有其他一些例子,但我仍然在这个特殊的场景中挣扎。
这是我的Enum:
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
}
这是我的Enum Helper类:
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描述属性
将源映射到目的地到目前为止,我的映射配置如下:
Mapper.CreateMap<Result, Incident>()
.ForMember(dest => dest.Status,
opts => opts.MapFrom(src => src.state));
下面是缩略的Result类:
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属性是一个字符串
例如:
我的目标是得到 Incident.Status = "Resolved - Workaround"
从 Result.state = "1"
我一直在努力与自动apper语法使用我的EnumHelper类
如果有人能帮我解决这个问题,我将不胜感激:)
有两种方法:
-
与
对齐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,因为它更干净。