简体   繁体   English

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

[英]Map generic type that receives constructor parameters with Automapper

My questions is related to a specific scenario that I don't know how to handle it. 我的问题与我不知道如何处理的特定情况有关。 I have a mapper registered between Application and ApplicationModel and vice verse. 我在Application和ApplicationModel之间注册了一个映射器,反之亦然。 Now I am calling a method that returns an IPagedList 现在,我正在调用一个返回IPagedList的方法

GetApplications Method: GetApplications方法:

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

And this is where I get my error because PagedList doesn't have a default constructor when it tries to make the mapping. 这就是我得到错误的地方,因为PagedList尝试进行映射时没有默认的构造函数。

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

I tried to figure out how this is done with ConstructUsing but honestly I need help to structure the call correctly if that is the correct path 我试图弄清楚如何使用ConstructUsing完成操作,但是老实说,如果这是正确的路径,我需要帮助来正确构造调用

Bellow are the interface and the implementation of IPagedList 下面是IPagedList的接口和实现

Interface: 接口:

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

Implementation: 实现方式:

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

Use ProjectTo<ApplicationModel>() or map the IQueryable<Applications> to List<ApplicationModels> , then throw it into PagedList's constructor and won't deal with the default constructor issue in AutoMapper. 使用ProjectTo<ApplicationModel>()或将IQueryable<Applications>映射到List<ApplicationModels> ,然后将其扔到PagedList的构造函数中,将不会处理AutoMapper中的默认构造函数问题。

ProjectTo Example: ProjectTo示例:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM