automapper map dynamic object

笑着哭i 提交于 2019-12-09 13:31:18

问题


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?


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/14329356/automapper-map-dynamic-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!