0

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);
  • Does this answer your question? [I keep getting "needs to have a constructor with 0 args or only optional args. (Parameter 'type')"](https://stackoverflow.com/questions/60806455/i-keep-getting-needs-to-have-a-constructor-with-0-args-or-only-optional-args) – Yong Shun May 17 '23 at 00:22

1 Answers1

2

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>();
Adalyat Nazirov
  • 1,611
  • 2
  • 14
  • 28