Error deleting with Restapi and dot net core 3

Asked

Viewed 36 times

0

Good afternoon, I am mounting an application with . net core 3 and Rest api, all my methods(get, put, post) work, but delete does not. Trying to delete generates the following error:

System.InvalidOperationException: The entity type 'UM[]' was not found. Ensure that the entity type has been added to the model.

The classes are as follows: Entitis:

 public class UM
{
    public int Id { get; set; }
    public string Descricao { get; set; }
    public string Sigla { get; set; }
}

Controller:

[Route("api/[controller]")]
[ApiController]
public class UmController : ControllerBase
{
    private readonly IGeradorRepository _repo;//injeto o repositorio pela interface(dependency injection)

    public UmController(IGeradorRepository repo)
    {
        _repo = repo;
    }
    [HttpGet]
    public async Task<IActionResult> Get(){
        try
        {
            var results = await _repo.GetAllUMAsync();
            return Ok(results);
        }
        catch (System.Exception)
        {
            return this.StatusCode(StatusCodes.Status500InternalServerError, "Falha no banco de dados");
        }
    }
    [HttpGet("{UmId}")]
    public async Task<IActionResult> Get(int UmId){
        try
        {
            var results = await _repo.GetAllUMAsyncById(UmId);
            return Ok(results);
        }
        catch (System.Exception)
        {
            return this.StatusCode(StatusCodes.Status500InternalServerError, "Falha no banco de dados");
        }
    }
    [HttpGet("getByDescricao/{descricao}")]
    public async Task<IActionResult> Get(string descricao){
        try
        {
            var results = await _repo.GetAllUMAsyncByDesc(descricao);
            return Ok(results);
        }
        catch (System.Exception)
        {
            return this.StatusCode(StatusCodes.Status500InternalServerError, "Falha no banco de dados");
        }
    }
    [HttpPost()]
    public async Task<IActionResult> Post(UM model){
        try
        {
            _repo.Add(model);

            if(await _repo.SaveChangesAsync()){
                return Created($"/api/um/{model.Id}", model);
            }

        }
        catch (System.Exception)
        {
            return this.StatusCode(StatusCodes.Status500InternalServerError, "Falha no banco de dados");
        }
        return BadRequest();
    }
    [HttpPut("{UmId}")]
    public async Task<IActionResult> Put(int UmId, UM model){
        try
        {
            var um = await _repo.GetAllUMAsyncByIdL(UmId);

            if(um == null) return NotFound();

            _repo.Update(model);

            if(await _repo.SaveChangesAsync()){
                return Created($"/api/um/{model.Id}", model);
            }

        }
        catch (System.Exception ex)
        {
            return this.StatusCode(StatusCodes.Status500InternalServerError, ex.ToString());
        }
        return BadRequest();
    }
    [HttpDelete("{UmId}")]
    public async Task<IActionResult> Delete(int UmId){
        try
        {
            var um = await _repo.GetAllUMAsyncByIdL(UmId);

            if(um == null) return NotFound();

            _repo.Delete(um);

            if(await _repo.SaveChangesAsync()){
                return Ok();
            }

        }
        catch (System.Exception ex)
        {
            return this.StatusCode(StatusCodes.Status500InternalServerError, ex.ToString());
        }
        return BadRequest();
    }
}

And the Repository interface

public interface IGeradorRepository
{
    //GERAL
    void Add<T>(T entity) where T : class;
    void Update<T>(T entity) where T : class;
    void Delete<T>(T entity) where T : class;

    Task<bool> SaveChangesAsync();

    //Listagens
    //UM
    Task<UM[]> GetAllUMAsync();
    Task<UM[]> GetAllUMAsyncById(int UmId)
    Task<UM[]> GetAllUMAsyncByDesc(string descricao);     

}

He points out an error on line 30 of this source:

 public class GeradorRepository : IGeradorRepository
{
    private readonly GeradorContext _context;

    public GeradorRepository(GeradorContext context)
    {
        _context = context;
    }
    #region metodos gerais
    public void Add<T>(T entity) where T : class
    {
        _context.Add(entity);
    }
    public void Update<T>(T entity) where T : class
    {
        _context.Update(entity);
    }
    public void Delete<T>(T entity) where T : class
    {
        _context.Remove(entity);
    }
    public async Task<bool> SaveChangesAsync()
    {
        return (await _context.SaveChangesAsync()) > 0;
    }

    #endregion
    #region metodos UM
    public async Task<UM[]> GetAllUMAsync()
    {
        IQueryable<UM> query = _context.UMs;
        return await query.ToArrayAsync();
    }

    public async Task<UM[]> GetAllUMAsyncByDesc(string descricao)
    {
        IQueryable<UM> query = _context.UMs
            .Where(u => u.Descricao.ToLower().Contains(descricao.ToLower()));
        return await query.ToArrayAsync();
    }

    public async Task<UM[]> GetAllUMAsyncById(int UmId)
    {
        IQueryable<UM> query = _context.UMs
            .Where(u => u.Id == UmId);
        return await query.ToArrayAsync();
    }

    public async Task<UM[]> GetAllUMAsyncByIdL(int UmId)
    {
        IQueryable<UM> query = _context.UMs
           .AsNoTracking()
           .Where(u => u.Id == UmId);
        return await query.ToArrayAsync();
    }


    #endregion
}

Erro no postman

1 answer

0


In case you are looking for an Array of um here:

var um = await _repo.GetAllUMAsyncByIdL(UmId); // aqui retorna um array

and passing the array on delete rather than spend an Entity alone:

if(um == null) return NotFound();

_repo.Delete(um); //aqui você está passando um array no lugar de uma entity

the correct would be to pass only one:

_repo.Delete(um[0]);

Or change your logic to accept one array of um

  • Bruno, thanks for the answer, I do this search to confirm if this item really exists, how can I pass the Entity with the correct data?

  • The signature of your delete method, just wait for an Entity... loop the return of Getallumasyncbyidl, or pass the first parameter: a[0].

  • Show, it worked, thank you very much.

  • @Ronaldoalves of nothing ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.