Dictionary map to an object using Automapper

前端 未结 6 558
执笔经年
执笔经年 2020-11-29 07:50

Below code is just for this question

I am having a class like

public User class
{
 public string Name{get;set;}
 public string Age{get;set;
}
         


        
6条回答
  •  感情败类
    2020-11-29 08:22

    AutoMapper maps between properties of objects and is not supposed to operate in such scenarios. In this case you need Reflection magic. You could cheat by an intermediate serialization:

    var data = new Dictionary();
    data.Add("Name", "Rusi");
    data.Add("Age", "23");
    var serializer = new JavaScriptSerializer();
    var user = serializer.Deserialize(serializer.Serialize(data));
    

    And if you insist on using AutoMapper you could for example do something along the lines of:

    Mapper
        .CreateMap, User>()
        .ConvertUsing(x =>
        {
            var serializer = new JavaScriptSerializer();
            return serializer.Deserialize(serializer.Serialize(x));
        });
    

    and then:

    var data = new Dictionary();
    data.Add("Name", "Rusi");
    data.Add("Age", "23");
    var user = Mapper.Map, User>(data);
    

    If you need to handle more complex object hierarchies with sub-objects you must ask yourself the following question: Is Dictionary the correct data structure to use in this case?

提交回复
热议问题