Automapper枚举说明属性

时间:2015-06-08 13:58:41

标签: c# automapper

我难以从枚举描述属性进行映射。我一直在寻找一个有用的例子,运气很少。我知道还有其他一些例子,但我仍然在努力应对这种特殊情况。

这是我的枚举:

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();
    }
}

我的目标是通过枚举说明属性

将源映射到目标

以下是我目前在映射配置中所拥有的内容:

  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; }
}

这是简短的Incident类:

public class Incident
{
    public string Id{ get; set; }
    public string Status{ get; set; }
}

注意:Result类的state属性是一个字符串

例如:

我的目标是获得

 Incident.Status = "Resolved - Workaround"

来自

 Result.state = "1"

我一直在努力使用自动播放器语法来与我的EnumHelper类一起使用

如果有人可以帮我解决这个问题,我们将不胜感激:)

1 个答案:

答案 0 :(得分:2)

两种方法:

  1. stdio: [0, 'pipe', 'pipe']内联:

    ResolveUsing
  2. 使用自定义 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);    
        }
    }
    
  3. 我推荐#2,因为它更干净。