簡體   English   中英

DTO的Generics列表

[英]List of Generics for DTO

我正在.Net Core 5 中構建一個 WebAPI 項目。 output 始終是所有端點的分頁結果。

因此,我為分頁的 output 創建了一個 DTO,如下所示:

public class PagedCommodityListDto
{
    /// <summary>
    /// The total number of items
    /// </summary>
    public int TotalItems { get; set; }
    /// <summary>
    /// The current page
    /// </summary>
    public int Page { get; set; }
    /// <summary>
    /// The list of paged items
    /// </summary>
    public List<CommodityDto> Items { get; set; }
}

如您所見,它包含端點返回的真實對象的列表,在上面的示例中,它是 CommodityDto

Dto的使用和填寫方式如下:

public static BusinessLogic.Dto.PagedCommodityListDto GetCommmodities(int page, ...)
{
    //Query that extracts the values from the data layer
    IQueryable<BusinessLogic.Dto.CommodityDto> commodities = MyQuery;
    
    //Logic for the paging...
    int totalItems = commodities.Count();
    skip = (page - 1) * pageSize;
    commodities = commodities.Skip(skip).Take(pageSize);

    BusinessLogic.Dto.PagedCommodityListDto pcl = new BusinessLogic.Dto.PagedEconomicDataDto();
    pcl.Items = commodities.ToList();
    pcl.TotalItems = totalItems;
    pcl.Page = page;
    
    return pcl;
}

現在,我在分頁 DTO 的 Items 屬性中添加了或多或少的 30 個端點,每個端點都有不同的實體 DTO,因為每個實體的屬性都不同,因此有 30 個 DTO。

我的問題是:我是否必須為“分頁容器”創建30 個額外的 DTO ,或者有一種方法可以使公共列表項 { get; 放; } 通用的?

請注意,API 必須具有有效的 Swagger 並返回 object 定義為 Z594C103F2C6E04C0C241AZ0 中的每個方法,如下所示:5031

[HttpGet]
[ApiVersion("1.0")]
[Route("List")]
[ProducesResponseType(typeof(BusinessLogic.Dto.PagedCommodityListDto), 200)]
public async Task<ActionResult> MethodName(....)
{
    return Ok(Models.Repository.Commodity.GetCommmodities(page, ....));
}

你可以這樣做

public class PaginationViewModel
    {
        public int PageNumber { get; set; }
        public int PageSize { get; set; }
        public int? TotalRecords { get; set; }
        public int? TotalPages => TotalRecords.HasValue ? (int)Math.Ceiling(TotalRecords.Value / (double)PageSize) : (int?)null;
                
    }


    public class PagedResult<T>
    {
        public PagedResult(IEnumerable<T> results, int pageNumber, int pageSize, int? totalRecords)
        {
            Results = new List<T>(results);
            PagingInfo = new PaginationViewModel
            {
                PageNumber = pageNumber,
                PageSize = pageSize,
                TotalRecords = totalRecords,
            };
        }
        public List<T> Results { get; private set; }
        public PaginationViewModel PagingInfo { get; set; }
    }

你像這樣使用

var pagedResult = new PagedResult<your model>(your model, pageNumber, 20, totalRows);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM