Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a Student object:

public class Student
{
    public 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.

like image 513
Daniel T. Avatar asked Sep 21 '10 02:09

Daniel T.


People also ask

How do I use AutoMapper to list a map?

How do I use AutoMapper? First, you need both a source and destination type to work with. The destination type's design can be influenced by the layer in which it lives, but AutoMapper works best as long as the names of the members match up to the source type's members.

Does AutoMapper map both ways?

Yes, or you can call CreateMap<ModelClass, ViewModelClass>(). ReverseMap() .


1 Answers

You'll need a custom type converter:

Mapper.CreateMap<Student, int>().ConvertUsing(src => src.Id);
like image 112
Jimmy Bogard Avatar answered Sep 25 '22 04:09

Jimmy Bogard