Automapper 6 CustomList <tsource>到CustomList2 <tdest>不映射项目

时间:2017-11-15 16:56:51

标签: c# automapper-6

我有两种PagedList<T>类型。 Data.PagedList<T>实施IList<T>ViewModels.PagedList<T>继承List<T>。我正在尝试从Data.PagedList<Comments>映射到ViewModels.PagedList<CommentsVM>。我有两个PagedLists的开放式通用映射和一个Comment的映射 - &gt; CommentVM,但在映射之后,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);

此时PageNumberPageSizeTotalCount都在comments上正确设置,但它包含0项,因此我必须这样做:

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

    return result;
}

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

0 个答案:

没有答案