Automapper将ExpandoObject转换为自定义对象的字典

时间:2019-05-22 15:14:19

标签: c# automapper expandoobject

我有一个expandoObject,例如

var attributeToMapFrom = new ExpandoObject();
attributeToMapFrom.Add("1", "Attribute1");
attributeToMapFrom.Add("2", "Attribute2");

我的应用程序中还有一个名为“ CustomAttribute”的类

public class CustomAttribute
{
    public int Id;
    public string AttributeValue;
}

另一个使用字典的地方:

var dict = new dictionary<int, CustomAttribute>();

我想使用Automapper将expandoObject中的值映射到Dictionary中,以便最终得到一个包含以下内容的字典:

Key  |  Value
1    |  CustomAttribute{Id = 1, AttributeValue = "Attribute1"}
2    |  CustomAttribute{Id = 2, AttributeValue = "Attribute2"}

我想这样映射它:

var attributeToMapFrom = new ExpandoObject();

attributeToMapFrom.Add("1", "Attribute1");
attributeToMapFrom.Add("2", "Attribute2");

var mappedAttributes = new Dictionary<int, CustomAttribute>();
this.Mapper.Map(attributeToMapFrom, mappedAttributes);

我在映射器配置中使用以下内容:

CreateMap<KeyValuePair<string, object>,CustomAttribute>()
            .ForMember(dest => dest.AttributeId, src => src.MapFrom(t => Convert.ToInt32(t.Key)));


       CreateMap<KeyValuePair<string, object>, KeyValuePair<int, CustomAttribute>>()
  .ConstructUsing( x => new KeyValuePair<int, CustomAttribute>( Convert.ToInt32(x.Key), x.MapTo<CustomAttribute>() ) );

我认为第二个createmap将创建字典的keyValuePairs,使用第一个创建值。

任何帮助将不胜感激。

0 个答案:

没有答案
相关问题