2

I have have two PagedList<T> types. Data.PagedList<T> implements IList<T>, ViewModels.PagedList<T> inherits List<T>. I'm trying to map from Data.PagedList<Comments> to ViewModels.PagedList<CommentsVM>. I have an open generic mapping for the two PagedLists and a mapping for Comments -> CommentsVM, but after mapping, the ViewModels.PagedList<CommentsVM> has all of its properties set, but it contains 0 items.

Data.PagedList<T>:

public class PagedList<T> : IList<T>
{
    private IList<T> _innerList;
    private int _totalCount;
    private int _pageSize;
    private int _pageNumber;

    public PagedList()
    {
        _innerList = new List<T>();
    }

    public PagedList(IList<T> existingList)
    {
        _innerList = existingList;
    }

    public int TotalCount
    {
        get { return _totalCount; }
        set { _totalCount = value; }
    }

    public int PageSize
    {
        get { return _pageSize; }
        set { _pageSize = value; }
    }

    public int PageNumber
    {
        get { return _pageNumber; }
        set { _pageNumber = value; }
    }

    //IList implementation...
}

ViewModels.PagedList<T>:

public class PagedList<T> : List<T>
{
    public PagedList()
    {
    }

    public PagedList(IEnumerable<T> collection) : base(collection) { }

    public int PageNumber { get; set; }

    public int PageSize { get; set; }

    public int TotalCount { get; set; }
}

Mapping Config:

CreateMap(typeof(Data.PagedList<>), typeof(ViewModels.PagedList<>));
CreateMap<Comments, CommentsVM>();

Mapping:

{
    IMapper mapper = MapperConfig.EntityWebMapper;

    Data.PagedList<Comments> comments = Repository.GetAccountComments(accountID, pageNum, pageSize);

    var result = mapper.Map<ViewModels.PagedList<CommentsVM>>(comments);

At this point PageNumber, PageSize, and TotalCount are all set correctly on comments, but it contains 0 items so I have to do this:

    foreach (var c in comments)
        result.Add(mapper.Map<CommentsVM>(c));

    return result;
}

My expectation was since automapper can map List to List, it would be able to do the same here once I added the open generics mapping between PagedLists. Why isn't it mapping the list items automatically? Can it?

xr280xr
  • 12,621
  • 7
  • 81
  • 125
  • I think by default automapper will map List to List. If you remove `CreateMap(typeof(Data.PagedList<>), typeof(ViewModels.PagedList<>));` from your mapping configuration and then map the objects you'll see that the comments list will map correctly - however your defined properties will obviously not. So we can probably hypothesize that when a mapping is defined the default behavior of List to List will not take effect and a full mapping definition needs to be provided. – TheRock Nov 20 '17 at 20:44

0 Answers0