2

我有两种PagedList<T>类型。Data.PagedList<T>实现IList<T>ViewModels.PagedList<T>继承List<T>。我正在尝试从映射Data.PagedList<Comments>ViewModels.PagedList<CommentsVM>. 我有两个 PagedLists 的开放通用映射和 Comments -> CommentsVM 的映射,但映射后,ViewModels.PagedList<CommentsVM>它的所有属性都已设置,但它包含 0 个项目。

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; }
}

映射配置:

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

映射:

{
    IMapper mapper = MapperConfig.EntityWebMapper;

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

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

此时PageNumber,PageSizeTotalCount都正确设置在 上comments,但它包含 0 个项目,所以我必须这样做:

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

    return result;
}

我的期望是因为 automapper 可以将 List 映射到 List,一旦我添加了 PagedLists 之间的开放泛型映射,它就可以在这里做同样的事情。为什么它不自动映射列表项?它可以?

4

0 回答 0