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);
}
}
I tried [HttpPost("ActualizarPedido")] // Internal server error
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.