Home > Back-end >  Internal server error when doing Update on Entity Framework
Internal server error when doing Update on Entity Framework

Time:06-25

I have a front on angular 14 and a backend on EF in .net core, I don´t understand why the code blows when it reaches _context.Pedido.Update(pedido);

[HttpPatch("ActualizarPedido")] //500 (Internal Server Error)
 public async Task<ActionResult<Pedidos>> ActualizarPedido([FromBody] Pedidos pedido)
        {
            if (string.IsNullOrEmpty(pedido.IdPedido.ToString()))
            {
                return BadRequest("Request is incorrect");
            }

            var result = await _context.Pedido.FindAsync(pedido.IdPedido);

            if (result == null)
            {
                return NotFound();
            }
            else {
                _context.Pedido.Update(pedido);
                await _context.SaveChangesAsync();
                return Ok(pedido);
            }
        }

The data is normal data image

I tried [HttpPost("ActualizarPedido")] // Internal server error

CodePudding user response:

In the Entity Framework working structure, it tracks an entity brought from the database with the tracker mechanism. Therefore, you cannot directly update an object sent by the client, even if its id is the same. To do this, map the pedido object sent by the client to the result object as follows;

result.DireccionClientte = pedido.DireccionClientte;

//After that you can update your entity.
_context.Pedido.Update(result);
await _context.SaveChangesAsync();

Also, I should point out, never present the entity to the client. You should create DTO instead.

CodePudding user response:

It turns out that EF can have more than one entity, a try catch showed me that, this is the working code:

[HttpPatch("ActualizarPedido")]         
        public async Task<ActionResult<Pedidos>> ActualizarPedido([FromBody] Pedidos pedido)
        {
            if (string.IsNullOrEmpty(pedido.IdPedido.ToString()))
            {
                return BadRequest("Request is incorrect");
            }

            var result = await _context.Pedido.FindAsync(pedido.IdPedido);

            if (result == null)
            {
                return NotFound();
            }
            else {
                try
                {
                    result.Detalle = pedido.Detalle;
                    result.TelefonoCliente = pedido.TelefonoCliente;
                    result.DireccionCliente = pedido.DireccionCliente;
                    result.NombreCliente = pedido.NombreCliente;
                    
                    _context.Pedido.Update(result);
                    await _context.SaveChangesAsync();
                    return Ok(result);
                }
                catch (System.Exception e)
                {
                    Console.WriteLine(e);
                    return StatusCode(500, "Internal Server Error");
                }
                
            }
        }
  • Related