列表与数组
AutoMapper
配置了两个类型的映射, 但不包含数组或列表的映射配置. 实际上, AutoMapper
支持:
IEnumerable
IEnumerable<T>
ICollection
ICollection<T>
ILIst
IList<T>
List<T>
Array
使用的时候, 只需要执行 Map
的时候配置好返回的类型即可.
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);
处理 null 集合
在映射集合属性的时候, 如果属性值为 null
, 不会映射为 null
, 而是映射成长度为 0 的集合. 这一点与 EF 和 Fx 的设计原则是一样的, 默认集合不允许为 null
.
通过配置 AllowNullCollections
属性为 true
来配置.
var conf = new MapperConfiguration(cfg => {
cfg.AllowNullCollections = true;
cfg.CreateMap<...
});
该特性可以使用 ALlowNull
和 DoNotAllowNull
来复写.
集合中的多态元素
场景:
- 存在多态类型模型
- 使用父类或接口来定义集合
- 集合元素是具体的子类
处理办法是, AutoMapper
配置中需要配置子类型的映射关系. 使用 Include
方法:
var configuration = new MapperConfiguration(c=> {
c.CreateMap<ParentSource, ParentDestination>()
.Include<ChildSource, ChildDestination>(); // 没有该配置, 会默认按照基类型转换
c.CreateMap<ChildSource, ChildDestination>();
});