0

Can you show me the right way of Mapping if I have two similar classes with difference in one property.

// DatabaseCamper.Gender is string that holds either "M" or "F"
// ViewModelCamper.gender is enum of type Gender

I presume it should be like this:

Mapper.CreateMap<DatabaseCamper, ViewModelCamper>().ForMember(x => x.Gender, ...

Could you finish this snippet?

Thanks.

UPD. or let's add a bit of salt to it. What if I have a property in mapping Destination class (ViewModelCamper in this case) that I don't initially have in the Source class, and the value should be calculated?

iLemming
  • 34,477
  • 60
  • 195
  • 309
  • Possible duplicate of [How to use AutoMapper .ForMember?](https://stackoverflow.com/questions/6985000/how-to-use-automapper-formember) – jpaugh Mar 14 '18 at 14:06

1 Answers1

3

Use IValueResolver (or IValueFormatter if going to string). For example, assuming the field is nullable if not specified, because it simplifies error handling...

public class GenderValueResolver : ValueResolver<string, Gender?>
{
    protected override Gender? ResolveCore(string source)
    {
        if (source.StartsWith("M", System.StringComparison.OrdinalIgnoreCase))
        {
            return Gender.Male;
        }

        else if (source.StartsWith("F", System.StringComparison.OrdinalIgnoreCase))
        {
            return Gender.Female;
        }

        return null;
    }
}

public class GenderValueFormatter : ValueFormatter<Gender?>
{
    protected override string FormatValueCore(Gender? value)
    {
        switch (value)
        {
            case Gender.Male:
                return "M";
            case Gender.Female:
                return "F";
            default:
                return null;
        }
    }
}

usage...

.ForMember(dest => dest.Gender, opt => opt.ResolveUsing(typeof(GenderValueResolver)).FromMember(src => src.Gender))

or

.ForMember(dest => dest.Pages, opt => opt.AddFormatter<GenderValueFormatter>())
John Meyer
  • 465
  • 2
  • 11