tags:

views:

158

answers:

1

I have a source object that looks like this:

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

The enums are decorated with a custom [Description] attribute that provides a string representation, and I have an extension method .GetDescription() that returns it. How do I map these enum properties using that extension?

I'm trying to map to an object like this:

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

I think a custom formatter is my best bet, but I can't figure out how to add the formatter and specify which field to map from at the same time.

A: 

Argh, idiot moment. Didn't realize I could combine ForMember() and AddFormatter() like this:

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

Problem solved.

Seth Petry-Johnson
Unless you need to map both, I'd also suggest just leaving the names the same, and just add the formatter. It's less configuration that way.
Jimmy Bogard
That's generally the approach I take, unless I have a really good reason otherwise. This came out of some testing I was doing and wanted to make sure the hard case was at least _possible_. Thanks!
Seth Petry-Johnson

related questions