简体   繁体   English

automapper map动态对象

[英]automapper map dynamic object

I am working with Automapper and need to achieve the following mapping but not sure how it can be done. 我正在使用Automapper,需要实现以下映射,但不确定如何完成。

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. 我想将Dictionary对象映射到动态对象,因此键是对象的属性,而字典的值是动态对象中的属性值。

Can this be achieve with automapper and if so, how? 这可以通过automapper来实现,如果是这样,怎么做?

You can simply get Dictionary from ExpandoObject and fill it with original dictionary values 您只需从ExpandoObject获取Dictionary并使用原始字典值填充它

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

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. 如果要包含更多或不同的结果,请在GetProperties方法中指定不同的BindingFlags 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 . 显然,以下示例不需要类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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM