Automapper Mapping Multiple Properties to Single Property

前端 未结 2 1331
难免孤独
难免孤独 2021-01-18 14:01

I am need help mapping my Domain Object to a ViewModel for use with my C#/MVC App

In the FormAnswer Class there can only be 1 Answer Type (AnswerCurrency, AnswerDate

2条回答
  •  别那么骄傲
    2021-01-18 15:00

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

提交回复
热议问题