automapper地图动态对象 [英] automapper map dynamic object

查看:195
本文介绍了automapper地图动态对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我与Automapper工作,需要实现以下映射,但不知道它是如何完成的。

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

我要Dictionary对象映射到一个动态对象,因此,关键是对象和字典的值的属性是在动态对象属性的值。

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.

可这是与automapper若然实现怎么样?

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

推荐答案

您可以简单地获得词典 ExpandoObject 并与原有的字典中的值填充

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

这篇关于automapper地图动态对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆