Dynamic mapapapper map object

I work with Automapper and should do the following mapping, but not sure how to do this.

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

Is it possible to do this with automapper, and if so, how?

+4
source share
2 answers

You can simply get the Dictionary from ExpandoObject and fill it with the 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; } 
+7
source

Here is an example, but if you drop the comment or refine your post, it can be more visual. 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 properties and values โ€‹โ€‹of a public instance as follows:

 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 a different BindingFlags in the GetProperties method. If this does not answer your question, leave a comment.

Alternatively, assuming you are working with a dynamic object and anonymous types, the approach is similar. The following example obviously does not require the Foo class.

 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)); 
0
source

All Articles