代码之家  ›  专栏  ›  技术社区  ›  Seth Petry-Johnson

automapper:将枚举映射到其[description]属性

  •  5
  • Seth Petry-Johnson  · 技术社区  · 14 年前

    我有一个看起来像这样的源对象:

    private class SourceObject {
        public Enum1 EnumProp1 { get; set; }
        public Enum2 EnumProp2 { get; set; }
    }
    

    这些枚举是用一种习惯来装饰的 [Description] 提供字符串表示的属性,我有一个扩展方法 .GetDescription() 它会返回。如何使用该扩展映射这些枚举属性?

    我试图映射到这样的对象:

    private class DestinationObject {
        public string Enum1Description { get; set; }
        public string Enum2Description { get; set; }
    }
    

    我认为自定义格式化程序是我的最佳选择,但我不知道如何添加格式化程序 同时指定要映射的字段。

    1 回复  |  直到 14 年前
        1
  •  7
  •   Seth Petry-Johnson    14 年前

    啊,白痴时刻。没有意识到我可以像这样组合formember()和addformatter():

    Mapper.CreateMap<SourceObject, DestinationObject>()
        .ForMember(x => x.Enum1Desc, opt => opt.MapFrom(x => x.EnumProp1))
        .ForMember(x => x.Enum1Desc, opt => opt.AddFormatter<EnumDescriptionFormatter>())
        .ForMember(x => x.Enum2Desc, opt => opt.MapFrom(x => x.EnumProp2))
        .ForMember(x => x.Enum2Desc, opt => opt.AddFormatter<EnumDescriptionFormatter>());
    

    问题解决了。