简体   繁体   English

ASP.NET 内核 Web API 检索 ZDB974238714CA8DE634A7CE1D083A1 中的空白记录

[英]ASP.NET Core Web API retrieves blank record in API GET Request

I am using ASP.NET Core Web API.我正在使用 ASP.NET 核心 Web API。 I have these models:我有这些模型:

public abstract class EntityBase
{
    [Key]
    public int Id { get; set; }
}

public class Mandate : EntityBase
{
    public int? MerchantId { get; set; }

    public DateTime DueDate { get; set; }
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }

    [ForeignKey("MerchantId")]
    public virtual Merchant Merchant { get; set; }
}

Model: Mandate Model:授权

ViewModel (Dto):视图模型(Dto):

public class MandateGetDto
{
    public int? MerchantId { get; set; }
    public DateTime DueDate { get; set; }
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
}

IBaseRepository: IBase 存储库:

public interface IBaseRepository<T> where T : BaseEntity
{

    Task<IEnumerable<T>> GetAll();
    bool EntityExists(long id);
}

BaseRepository:基础存储库:

public class BaseRepository<T> : IBaseRepository<T> where T : AuditableBaseEntity
{
    private readonly DDMDbContext _context;
    private DbSet<T> _entities;

    public BaseRepository(DDMDbContext context)
    {
        _context = context;
        _entities = context.Set<T>();
    }

    public async Task<IEnumerable<T>> GetAll()
    {
        var list = await _entities.ToListAsync();
        return list;
    }
    public bool EntityExists(long id)
    {
        return _entities.Any(x => x.Id == id);
    }
}

EntityMapper:实体映射器:

    public MandateGetDto FromMandateToMandateGetDto(Mandate mandate)
    {
        MandateGetDto mandateDto = new MandateGetDto();
        mandateDto.MerchantId = mandate.MerchantId;
        mandateDto.DueDate = mandate.DueDate;
        mandateDto.StartDate = mandate.StartDate;
        mandateDto.EndDate = mandate.EndDate;

        return mandateDto;
    }

UnitOfWork:工作单位:

public class UnitOfWork : IUnitOfWork
{
    private readonly DContext _context;

    public UnitOfWork(DContext context)
    {
        _context = context;
    }
    #region Mandate
    private readonly IBaseRepository<Mandate> _mandateRepository;

    public IBaseRepository<Mandate> MandateRepository => _mandateRepository ?? new BaseRepository<Mandate>(_context);
    # endregion

    public void Dispose()
    {
        if (_context != null)
        {
            _context.Dispose();
        }
    }
}

Below is the code I have written for the Mandate service which retrieves all the records for the mandates.下面是我为 Mandate 服务编写的代码,它检索所有的授权记录。

MandateService:授权服务:

    public async Task<ResponsePagination<GenericPagination<MandateGetDto>>> GetAll(int page, int sizeByPage)
    {
        string nextRoute = null, previousRoute = null;
        IEnumerable<Mandate> data = await _unitOfWork.MandateRepository.GetAll();

        var mapper = new EntityMapper();
        var mandatesDto = data.Select(m => mapper.FromMandateToMandateGetDto(m)).ToList();

        GenericPagination<MandateGetDto> objGenericPagination = GenericPagination<MandateGetDto>.Create(mandatesDto, page, sizeByPage);
        ResponsePagination<GenericPagination<MandateGetDto>> response = new ResponsePagination<GenericPagination<MandateGetDto>>(objGenericPagination);
        response.CurrentPage = objGenericPagination.CurrentPage;
        response.HasNextPage = objGenericPagination.HasNextPage;
        response.HasPreviousPage = objGenericPagination.HasPreviousPage;
        response.PageSize = objGenericPagination.PageSize;
        response.TotalPages = objGenericPagination.TotalPages;
        response.TotalRecords = objGenericPagination.TotalRecords;
        response.Data = objGenericPagination;

        if (response.HasNextPage)
        {
            nextRoute = $"/mandates?page={(page + 1)}";
            response.NextPageUrl = _uriPaginationService.GetPaginationUri(page, nextRoute).ToString();
        }
        else
        {
            response.NextPageUrl = null;
        }

        if (response.HasPreviousPage)
        {
            previousRoute = $"/mandates?page={(page - 1)}";
            response.PreviousPageUrl = _uriPaginationService.GetPaginationUri(page, previousRoute).ToString();
        }
        else
        {
            response.PreviousPageUrl = null;
        }
        return response;
    }

    public async Task<IEnumerable<Mandate>> GetMandates()
    {
        return await _unitOfWork.MandateRepository.GetAll();
    }

startup.cs:启动.cs:

services.AddTransient<IMandateService, MandateService>();

Controller: Controller:

[Produces("application/json")]
[ApiController]
[ApiVersion("1.0")]
public class AdminController : ControllerBase
{
    private readonly IMerchantService _merchantService;
    private readonly DDMDbContext _context;

    public AdminController(DDMDbContext context, IMerchantService merchantService)
    {
        _merchantService = merchantService;
        _context = context;
    }
    [HttpGet("mandates")]
    [Authorize]
    public async Task<ResponsePagination<GenericPagination<MandateGetDto>>> GetAllMyMandates(int page, int sizeByPage)
    {
        return await _mandateService.GetAll(page, sizeByPage);
    }

}

When I used POSTMAN for the Get Request, I got this response:当我将 POSTMAN 用于获取请求时,我得到了以下响应:

{
    "current_page": 0,
    "page_size": 0,
    "total_pages": -2147483648,
    "total_records": 1,
    "has_next_page": false,
    "has_previous_page": false,
    "data": []
}

Data is blank while total record is 1.数据为空白,总记录为 1。

How do I resolve this?我该如何解决这个问题?

Thanks谢谢

You have not shown us the principal part of your code, which is the controller您尚未向我们展示您的代码的主要部分,即controller

Controller is the reason why your web API even works. Controller是您的 web API 甚至可以工作的原因。 So, if you have misconfigured something, it should be present in the controller first or then somewhere else.因此,如果您配置错误,它应该首先出现在 controller 中,然后出现在其他地方。

Show us the code for the controller.向我们展示 controller 的代码。

Edit编辑

I am not sure if DbSet is appropriate for the usage, but using the context object works for me.我不确定 DbSet 是否适合使用,但使用上下文 object 对我有用。

You should use你应该使用

_context.MandateOrWhateverElseItIs.ToListAsync();

instead of using而不是使用

_entities.ToListAsync();

Using the DbSet can be an issue, I recommend using the context.使用 DbSet 可能是个问题,我建议使用上下文。 My application works fruitfully with context.我的应用程序在上下文中卓有成效。

Edit编辑

This is your code in BaseRepository这是您在 BaseRepository 中的代码

public class BaseRepository<T> : IBaseRepository<T> where T : AuditableBaseEntity
{
    private readonly DDMDbContext _context;
    private DbSet<T> _entities;

    public BaseRepository(DDMDbContext context)
    {
        _context = context;
        _entities = context.Set<T>();
    }

    public async Task<IEnumerable<T>> GetAll()
    {
        var list = await _entities.ToListAsync();
        return list;
    }
    public bool EntityExists(long id)
    {
        return _entities.Any(x => x.Id == id);
    }
}

What you should change it to is您应该将其更改为

public class BaseRepository<T> : IBaseRepository<T> where T : AuditableBaseEntity
{
    private readonly DDMDbContext _context;
    private DbSet<T> _entities;

    public BaseRepository(DDMDbContext context)
    {
        _context = context;
        _entities = context.Set<T>();
    }

    public async Task<IEnumerable<T>> GetAll()
    {
        //Changes are here
        var list = await _context.EntitiesOrWhateverElseItIs.ToListAsync(); //I don't know what the option is, you can look it inside the autocomplete. Be sure to change EntitiesOrWhateverElseItIs with the option you see in autocomplete menu
        return list;
    }
    public bool EntityExists(long id)
    {
        return _entities.Any(x => x.Id == id);
    }
}

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

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