我有一个Student
对象:
public class Student
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
还有一个Classroom
对象:
public class Classroom
{
public List<Student> Students { get; set; }
}
我想使用 AutoMapper 将学生列表转换为学生 ID 列表:
public class ClassroomDTO
{
public List<int> StudentIds { get; set; }
}
如何配置 AutoMapper 来进行这种转换?
回答:
为了扩展我的问题和吉米的回答,这就是我最终要做的事情:
Mapper.CreateMap<Student, int>().ConvertUsing(x => x.Id);
Mapper.CreateMap<Classroom, ClassroomDTO>()
.ForMember(x => x.StudentIds, y => y.MapFrom(z => z.Students));
AutoMapper 足够聪明,可以完成剩下的工作。