Rusi Nova Rusi Nova - 7 months ago 93
C# Question

Dictionary <string,string> map to an object using Automapper

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;

I am having a dictionary like

Dictionary<string,string> data= new Dictionary<string,string>();

User user= new User();

Now i want to map
object to this
. Automapper maps properties of objects but in my case there a dictionary and object.

So, Please suggest me how can i do this


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<string, string>();
data.Add("Name", "Rusi");
data.Add("Age", "23");
var serializer = new JavaScriptSerializer();
var user = serializer.Deserialize<User>(serializer.Serialize(data));

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

    .CreateMap<Dictionary<string, string>, User>()
    .ConvertUsing(x =>
        var serializer = new JavaScriptSerializer();
        return serializer.Deserialize<User>(serializer.Serialize(x));

and then:

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

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