我这里的写法是使用这样的,反射一个实体:
private readonly IMapper _mapper;
var model = _mapper.Map<source>(dest);
错误的写法
var result=_mapper.Map<List<dest>>(source);
var result=_mapper.Map<List<souce>,List<dest>>(source);
这两种写法最开始我是以为可以的,但我没有加Profile文件,所以报如下错误:
Missing type map configuration or unsupported mapping.
那么在services层使用IMapper如何反射集合?
var configuration = new MapperConfiguration(cfg => {
cfg.AllowNullCollections = true;
cfg.CreateMap<source, dest>();
});
var result = new Mapper(configuration).Map<List<dest>>(source);
官方的示例
var configuration = new MapperConfiguration(cfg => cfg.CreateMap<Source, Destination>());
var sources = new[]
{
new Source { Value = 5 },
new Source { Value = 6 },
new Source { Value = 7 }
};
IEnumerable<Destination> ienumerableDest = mapper.Map<Source[], IEnumerable<Destination>>(sources);
ICollection<Destination> icollectionDest = mapper.Map<Source[], ICollection<Destination>>(sources);
IList<Destination> ilistDest = mapper.Map<Source[], IList<Destination>>(sources);
List<Destination> listDest = mapper.Map<Source[], List<Destination>>(sources);
Destination[] arrayDest = mapper.Map<Source[], Destination[]>(sources);
如果不想那么复杂的每次去实例化一个MapperConfiguration
可以参考官方写的配置demo,将实例依赖注入容器中
Configuration — AutoMapper documentationhttps://docs.automapper.org/en/stable/Configuration.html官方给出的怎么映射集合和数组的链接如下:
可以自己新建一个MyProfile文件继承自automapper的Profile类
CreateMap<source, dest>().ReverseMap();
CreateMap<dest, source>().ReverseMap();
这时候在使用刚才的写法就不会报错。
var result= _mapper.Map<List<dest>>(source);