Search code examples
c#automapperautomapping

Automapping an array class


I have a destination object as

ArrayOfStudents[]

containing

StudentId, AddressInfo, MarksInfo

The source object is

public class Details
{
   public Student[] Student;

)

The Student class contains

StudentId, AddressInfo, MarksInfo

I want to map Student[] and ArrayOfStudents[]

I tried the following, but didn't work

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

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

How should I be mapping this case?

It throws the following are unmapped error

StudentId, AddressInfo, MarksInfo


Solution

  • With Automapper you map one type to another. When you do that, mapping an array of the same types will happen automatically.

    In your case, you will create a map between ArrayOfStudents and Student. It'll be a trivial map since the types and the names between both mapped types are the same:

    public class MappingProfile : Profile
    {
        public MappingProfile()
        {
            this.CreateMap<Student, ArrayOfStudents>();
    
            this.CreateMap<ArrayOfStudents, Student>();
        }
    }
    

    Now, where ever you intend to do the actual mapping (e.g. a RESTful controller), you do something like:

    public class MyController
    {
        private readonly IMapper mapper;
    
        public MyController(IMapper mapper)
        {
            this.mapper = mapper;
        }
    
        // Then in any of your methods:
        [HttpGet]
        public IActionResult MyMethod()
        {
            var objectsToMap = details.Student; // This is an array of Student type.
            var mappedObjects = this.mapper.Map(objectsToMap); // This will be an array of ArrayOfStudents.
            // do what you will with the mapped objects.
        }
    }
    

    Idea is, you register the mappings for types (including the types of the members in a type). Then mapping of collections of those types is automatically handled by Automapper.