开发者

How do I convert a list of objects to a list of integers using AutoMapper?

开发者 https://www.devze.com 2023-01-17 02:57 出处:网络
I have a Student object: public class Student { p开发者_Python百科ublic int Id { get; set; } public string FirstName { get; set; }

I have a Student object:

public class Student
{
    p开发者_Python百科ublic int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

And a Classroom object:

public class Classroom
{
    public List<Student> Students { get; set; }
}

I want to use AutoMapper to convert the list of students to a list of student IDs:

public class ClassroomDTO
{
    public List<int> StudentIds { get; set; }
}

How do I configure AutoMapper to do this conversion?

Answer:

To expand on my question and Jimmy's answer, this is what I ended up doing:

Mapper.CreateMap<Student, int>().ConvertUsing(x => x.Id);
Mapper.CreateMap<Classroom, ClassroomDTO>()
      .ForMember(x => x.StudentIds, y => y.MapFrom(z => z.Students));

AutoMapper was smart enough to do the rest.


You'll need a custom type converter:

Mapper.CreateMap<Student, int>().ConvertUsing(src => src.Id);
0

精彩评论

暂无评论...
验证码 换一张
取 消