Search code examples
c#asp.netautomapper

How can I get Auto Mapper to work with a custom list that inherits everything inside the List Class


I have this set as a Mapping Profiles

CreateMap<Stuff, StuffDto>();

This mapping works

StuffDto stuffDto = _mapper.Map<Stuff, StuffDto>(Stuff); 

And this mapping also works

List<StuffDto> stuffDtoList = _mapper.Map<List<Stuff>, List<StuffDto>>(Stuff);

However this mapping does not

PagesList<StuffDto> stuffDtoList = _mapper.Map<PagedList<Stuff>, PagesList<StuffDto>>(Stuff);

The error is : needs to have a constructor with 0 args or only optional args. Validate your configuration for details.

The PageList looks like

public class PagedList<T> : List<T>
{
    public PagedList(IEnumerable<T> items, int count, int pageNumber, int pageSize)
    {
        CurrentPage = pageNumber;
        TotalPages = (int)Math.Ceiling(count / (double)pageSize);
        PageSize = pageSize;
        TotalCount = count;
        AddRange(items);
    }

    public int CurrentPage { get; set; }
    public int TotalPages { get; set; }
    public int PageSize { get; set; }
    public int TotalCount { get; set; }

    public static async Task<PagedList<T>> CreateAsync(IQueryable<T> source, int pageNumber,
        int pageSize)
    {
        // get the count of items EX 200 total events
        var count = await source.CountAsync();
        var items = await source.Skip((pageNumber - 1) * pageSize).Take(pageSize).ToListAsync();
        return new PagedList<T>(items, count, pageNumber, pageSize);
    }
}

What do I need to do to get this to work/resolve like List does?

_mapper.Map<PagedList<Stuff>, PagesList<StuffDto>>(Stuff);

Solution

  • On the first glance you have three workarounds:

    1. In case PagedList is mutable (can add/remove items) you can map to existing pagedList instance. It might look like this
    PagesList<StuffDto> stuffDtoList = new PagedList<StuffDto>(Enumerable.Empty<StuffDto>(), ...);
    _mapper.Map<PagedList<Stuff>, PagesList<StuffDto>>(Stuff, stuffDtoList);
    
    1. Another approach is referenced to mapping generic List, and then craete PagedList
    List<StuffDto> stuffDtoList = _mapper.Map<List<Stuff>, List<StuffDto>>(Stuff);
    PagesList<StuffDto> pagedList = new PagedList<StuffDto>(stuffDtoList, ...);
    
    1. Create custom type converter as described here. And customize it as you wish
    CreateMap<Stuff, StuffDto>();
    CreateMap<PagedList<Stuff>, PagedList<StuffDto>>().ConvertUsing<PagedListTypeConverter>();