Automapper Mapping Multiple Properties to Single Property

ValueResolver is a good suggestion, especially if you have this pattern elsewhere. If you're looking for a quick and dirty version (that is, if this is the only place you need to handle this sort of situation), try this:

Mapper.CreateMap<FormAnswer, FormAnswerModel>()
    .ForMember(d => d.Answer, o => o.ResolveUsing(fa =>
        {
            string answer = String.Empty;
            if (fa.AnswerBool.HasValue)
            {
                return fa.AnswerBool.Value;
            }

            if(fa.AnswerCurrency.HasValue)
            {
                return fa.AnswerCurrency.Value;
            }

            if(fa.AnswerDateTime.HasValue)
            {
                return fa.AnswerDateTime;
            }

            if(!String.IsNullOrEmpty(fa.AnswerString))
            {
                return fa.AnswerString;
            }

            return answer;
        }
    ));

You could use a custom mapping lambda method but it seems like you would need more logic here. A custom resolver seems to be a good option in this case.

See Automapper wiki

https://github.com/AutoMapper/AutoMapper/wiki/Custom-value-resolvers

In the mapping options you can specify a opt.ResolveUsing<TResolver>() where TResolver inherits from ValueResolver<FormAnswer, string>

Also, if I need to know how to do something with Automapper I find that the unit tests provide very rich documentation.

Hope that helps.

Tags:

C#

Automapper