在Automapper 11.0.0版本中,当进行List到Dictionary的类型转换时,会抛出类型映射错误。此时需要手动设置Dictionary类型转换规则为CreateFromPairs:
using AutoMapper;
using System.Collections.Generic;
public class Foo
{
public string Name { get; set; }
public int Age { get; set; }
}
public class Bar
{
public Dictionary Properties { get; set; }
}
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap, Dictionary>()
.ConvertUsing(list => list.ToDictionary(x => x.Name, x => x.Age));
//手动设置Dictionary类型转换规则为CreateFromPairs
cfg.CreateMap, Bar>()
.ForMember(dest => dest.Properties, opt => opt.MapFrom(src => src));
});
var fooList = new List
{
new Foo { Name = "John", Age = 25 },
new Foo { Name = "Peter", Age = 30 },
new Foo { Name = "Bob", Age = 20 }
};
var mapper = config.CreateMapper();
var bar = mapper.Map, Bar>(fooList);
上述代码示例中,我们手动设置了List到Dictionary的类型转换规则,并映射到了Bar类的Properties属性中,从而成功解决了类型映射错误的问题。