amateur
amateur

Reputation: 44605

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?

Upvotes: 5

Views: 9038

Answers (2)

Ilya Ivanov
Ilya Ivanov

Reputation: 23626

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

Upvotes: 9

e_ne
e_ne

Reputation: 8459

Here's en example, but if you drop a comment or elaborate your post it could be more descriptive. Given this class:

class Foo
{
    public Foo(int bar, string baz)
    {
        Bar = bar;
        Baz = baz;
    }

    public int Bar { get; set; }
    public string Baz { get; set; }
}

You can create a dictionary of its public instance properties and values this way:

var valuesByProperty = foo.GetType().
     GetProperties(BindingFlags.Public | BindingFlags.Instance).
     ToDictionary(p => p, p => p.GetValue(foo));

If you want to include more or different results, specify different BindingFlags in the GetProperties method. If this doesn't answer your question, please leave a comment.

Alternatively, assuming you're working with a dynamic object and anonymous types, the approach is similar. The following example, clearly, doesn't require the class Foo.

dynamic foo = new {Bar = 42, Baz = "baz"};
Type fooType = foo.GetType();
var valuesByProperty = fooType.
    GetProperties(BindingFlags.Public | BindingFlags.Instance).
    ToDictionary(p => p, p => p.GetValue(foo));

Upvotes: 0

Related Questions