Automapper Mapping Multiple Properties to Single Property

给你一囗甜甜゛ 提交于 2020-01-03 12:57:53

问题


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, AnswerDateTime, AnswerBool,etc) this is enforced in the Database and Application Logic.

If a Answer exists it will needs to be to Mapped to the Answer Property in the FormAnswerModel if all values are null the Answer is a Empty String.

public class FormQuestion
{
   public int Id {get; set;)
   public string DataType {get; set;} 
   public string Question {get; set;} 
}

public class FormAnswer
{
   public int Id {get; set;)
   public int QuestionId {get; set;)
   public double? AnswerCurrency {get;set}
   public dateTime? AnswerDataTime {get;set}
   public bool? AnswerBool {get;set}
   public string AnswerString{get;set}
   public string AnswerText{get;set}
}

public class FormAnswerModel
{
   public int Id {get; set;)
   public int QuestionId {get; set;)
   public string Answer{get;set}
}

回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/9205241/automapper-mapping-multiple-properties-to-single-property

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!