Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

automapper map dynamic object

I am working with Automapper and need to achieve the following mapping but not sure how it can be done.

I want to map a Dictionary object to a dynamic object, so that the key is the property on the object and the value of the dictionary is the value of property in dynamic object.

Can this be achieve with automapper and if so, how?

like image 479
amateur Avatar asked Jan 15 '13 00:01

amateur


1 Answers

You can simply get Dictionary from ExpandoObject and fill it with original dictionary values

void Main()
{
    AutoMapper.Mapper.CreateMap<Dictionary<string, object>, dynamic>()
                     .ConstructUsing(CreateDynamicFromDictionary);

    var dictionary = new Dictionary<string, object>();
    dictionary.Add("Name", "Ilya");

    dynamic dyn = Mapper.Map<dynamic>(dictionary);

    Console.WriteLine (dyn.Name);//prints Ilya
}

public dynamic CreateDynamicFromDictionary(IDictionary<string, object> dictionary)
{
    dynamic dyn = new ExpandoObject();
    var expandoDic = (IDictionary<string, object>)dyn;

    dictionary.ToList()
              .ForEach(keyValue => expandoDic.Add(keyValue.Key, keyValue.Value));
    return dyn;
}
like image 146
Ilya Ivanov Avatar answered Oct 24 '22 18:10

Ilya Ivanov