AutoMapper官方文档(九)【列表和数组】
2017-11-28 13:56
344 查看
AutoMapper只需要配置元素类型,而不是任何可能使用的数组或列表类型。 例如,我们可能有一个简单的源和目标类型:
public class Source { public int Value { get; set; } } public class Destination { public int Value { get; set; } }
所有基本的泛型集合类型都被支持:
Mapper.Initialize(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);
具体而言,支持的源集合类型包括:
IEnumerable IEnumerable<T> ICollection ICollection<T> IList IList<T> List<T> Arrays
对于非泛型可枚举类型,仅支持未映射的可指定类型,因为AutoMapper将无法
“猜测”您尝试映射的类型。 如上例所示,没有必要显式配置列表类型,只有它们的成员类型。
映射到现有集合时,首先清除目标集合。 如果这不是你想要的,看看
AutoMapper.Collection。
集合中的多态元素类型
很多时候,我们的源和目标类型都可能有一个类型的层次结构。AutoMapper支持多态数组和集合,如果找到,则使用派生的源/目标类型。
public class ParentSource { public int Value1 { get; set; } } public class ChildSource : ParentSource { public int Value2 { get; set; } } public class ParentDestination { public int Value1 { get; set; } } public class ChildDestination : ParentDestination { public int Value2 { get; set; } }
AutoMapper仍然需要显式配置子映射,因为AutoMapper不能
“猜测”要使用的特定子目标映射。 以下是上述类型的示例:
Mapper.Initialize(c=> { c.CreateMap<ParentSource, ParentDestination>() .Include<ChildSource, ChildDestination>(); c.CreateMap<ChildSource, ChildDestination>(); }); var sources = new[] { new ParentSource(), new ChildSource(), new ParentSource() }; var destinations = Mapper.Map<ParentSource[], ParentDestination[]>(sources); destinations[0].ShouldBeInstanceOf<ParentDestination>(); destinations[1].ShouldBeInstanceOf<ChildDestination>(); destinations[2].ShouldBeInstanceOf<ParentDestination>();
相关文章推荐
- JNI官方文档翻译3-基本数据类型 字符串 数组
- TC官方文档翻译04----列表对象API(Tokyo Cabinet/Tokyo Tyarnt 文档系列)
- Swift 集合类型(Collection Type) 之 数组(array)(官方文档翻译及总结)
- 数据库官方在线文档列表(mysql, postgreSQL)
- 控件产品官方文档/手册/API列表汇总
- 【AutoMapper官方文档】DTO与Domin Model相互转换(下)
- AutoMapper官方文档(十一)【自定义类型转换器】
- AutoMapper官方文档(十二)【自定义值解析器】
- AutoMapper官方文档(十八)【条件映射,开放泛型,了解你的映射】
- React官方文档—9.列表 & Keys
- 【AutoMapper官方文档】DTO与Domin Model相互转换(中)
- 12 Three.js官方文档介绍的相关对象功能列表
- 【python】numpy库数组拼接快捷方式horizontal&vertical、np.c_、np.column_stack等官方文档详解与实例
- AutoMapper官方文档(一)【入门】
- Cocos Creator 动作列表(摘自官方文档)
- AutoMapper官方文档(十三)【值转换器,Null替换,Map行为前后】
- Python3.2官方文档教程- 列表
- 常用控件产品官方文档/手册/API列表 c#控件文档API列表 asp.net控件产品技术文档中文版
- 【AutoMapper官方文档】DTO与Domin Model相互转换(上)
- jQuery学习笔记--jqGrid方法列表 官方文档!