automapper怎么反射集合

文章讨论了在使用AutoMapper进行对象映射时遇到的问题,特别是关于映射集合的错误写法。通过创建MapperConfiguration,定义Profile并设置映射规则,可以避免Missingtypemapconfigurationorunsupportedmapping的错误。同时,文章提到了不同类型的集合映射示例,如List、Array等,并建议将配置注入到依赖注入容器中以简化代码。
摘要由CSDN通过智能技术生成

我这里的写法是使用这样的,反射一个实体:

 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官方给出的怎么映射集合和数组的链接如下:

Lists and Arrays — AutoMapper documentationhttps://docs.automapper.org/en/stable/Lists-and-arrays.html

可以自己新建一个MyProfile文件继承自automapper的Profile类

  CreateMap<source, dest>().ReverseMap();
   CreateMap<dest, source>().ReverseMap();

这时候在使用刚才的写法就不会报错。

var result= _mapper.Map<List<dest>>(source);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值