Automapper: map Enum to its [Description] attribute

I have a source object that looks like this:

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

Enums are decorated with a special attribute [Description]that provides a string representation, and I have an extension method .GetDescription()that returns it. How to match these enumeration properties with this extension?

I am trying to match an object like this:

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

I think this is the best option, but I can’t figure out how to add a formatter and specify which field will be displayed at the same time.

+5
source share
1 answer

Arg, idiot. I didn't understand that I could combine ForMember () and AddFormatter () as follows:

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

The problem is resolved.

+7
source

All Articles