[英]Error when doing code-first Entity Framework while having SQL Server installed on my computer
[英]Internal server error when doing Update on Entity Framework
我在 .net 核心中有一個 Angular 14 的前端和一個 EF 的后端,我不明白為什么代碼在到達 _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);
}
}
我試過 [HttpPost("ActualizarPedido")] // 內部服務器錯誤
在 Entity Framework 工作結構中,它使用跟蹤器機制跟蹤從數據庫中帶入的實體。 因此,您不能直接更新客戶端發送的對象,即使其 id 相同。 為此,將客戶端發送的pedido
對象映射到result
對象,如下所示;
result.DireccionClientte = pedido.DireccionClientte;
//After that you can update your entity.
_context.Pedido.Update(result);
await _context.SaveChangesAsync();
另外,我應該指出,永遠不要將實體呈現給客戶。 您應該改為創建 DTO。
事實證明,EF 可以有多個實體,try catch 告訴我,這是工作代碼:
[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");
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.