自动映射数组类

我有一个目标对象

ArrayOfStudents[]

含有

StudentId,    AddressInfo,    MarksInfo

源对象是

public class Details{
   public Student[] Student;

)

学生类包含

学生号、地址信息、标记信息

我想要地图Student[]ArrayOfStudents[]

我尝试了以下方法,但没有成功

Map.CreateMap<Student,ArrayOfStudents>()
.ReverseMap();

Map.CreateMap<Details.Student,ArrayOfStudents>()
.ReverseMap();

我应该如何绘制这个案例?

它抛出以下未映射错误

学生号、地址信息、标记信息


qq_遁去的一_1
浏览 80回答 1
1回答

有只小跳蛙

使用 Automapper,您可以将一种类型映射到另一种类型。当您这样做时,将自动映射相同类型的数组。ArrayOfStudents在您的情况下,您将创建和之间的地图Student。这将是一个简单的映射,因为两个映射类型之间的类型和名称是相同的:public class MappingProfile : Profile{&nbsp; &nbsp; public MappingProfile()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; this.CreateMap<Student, ArrayOfStudents>();&nbsp; &nbsp; &nbsp; &nbsp; this.CreateMap<ArrayOfStudents, Student>();&nbsp; &nbsp; }}现在,无论您打算在哪里进行实际映射(例如 RESTful 控制器),您都可以执行以下操作:public class MyController{&nbsp; &nbsp; private readonly IMapper mapper;&nbsp; &nbsp; public MyController(IMapper mapper)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; this.mapper = mapper;&nbsp; &nbsp; }&nbsp; &nbsp; // Then in any of your methods:&nbsp; &nbsp; [HttpGet]&nbsp; &nbsp; public IActionResult MyMethod()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; var objectsToMap = details.Student; // This is an array of Student type.&nbsp; &nbsp; &nbsp; &nbsp; var mappedObjects = this.mapper.Map(objectsToMap); // This will be an array of ArrayOfStudents.&nbsp; &nbsp; &nbsp; &nbsp; // do what you will with the mapped objects.&nbsp; &nbsp; }}想法是,您注册类型的映射(包括类型中成员的类型)。然后,这些类型的集合的映射由 Automapper 自动处理。
打开App,查看更多内容
随时随地看视频慕课网APP