映射使用Automapper接收构造函数参数的泛型类型

时间:2018-04-04 20:44:34

标签: c# automapper

我的问题与我不知道如何处理它的特定情况有关。 我在Application和ApplicationModel之间注册了一个mapper,反之亦然。 现在我正在调用一个返回IPagedList

的方法

GetApplications方法:

IPagedList<Application> GetApplications()
{
   IQueryable items = context.Applications...
   return new PagedList<Application>(items, 1, 10);
}

这是我收到错误的地方,因为PagedList在尝试进行映射时没有默认构造函数。

IPagedList<Application> applications = GetApplications();         
var toRet = Mapper.Map<IPagedList<ApplicationModel>>(applications); //here I get the error

我试图弄清楚如何使用ConstructUsing完成此操作但老实说,如果这是正确的路径,我需要帮助才能正确构建调用

Bellow是IPagedList的接口和实现

界面:

public interface IPagedList<T> : IList<T>
{
    int CurrentPage { get; }
    int TotalPages { get; }
    int PageSize { get; }
    int TotalCount { get; }
    bool HasPrevious { get; }
    bool HasNext { get; }
    IEnumerable<T> Items { get; }
}

实施

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

    public PagedList(IQueryable<T> source, int pageNumber, int pageSize) : this(source.AsEnumerable(), source.Count(), pageNumber, pageSize)
    {

    }

    public int CurrentPage { get; }
    public int TotalPages { get; }
    public int PageSize { get; }
    public int TotalCount { get; }
    public bool HasPrevious => CurrentPage > 1;
    public bool HasNext => CurrentPage < TotalPages;
    public IEnumerable<T> Items { get; }
}

1 个答案:

答案 0 :(得分:0)

使用ProjectTo<ApplicationModel>()或将IQueryable<Applications>映射到List<ApplicationModels>,然后将其投放到PagedList的构造函数中,并且不会处理AutoMapper中的默认构造函数问题。< / p>

ProjectTo示例:

var toRet = new PagedList<ApplicationModel>(context.Applications...ProjectTo<ApplicationModel>(), 1, 10);

相关问题