locked
Internal server error after deleting record and trying to retrieve last record RRS feed

  • Question

  • User2139392758 posted

    Best regards.

    I have this deleted method and error occurs on the highlighted line and I don't know what to do.

            [HttpDelete("{id}")]
            public async Task<ActionResult<Producto>> DeleteProducto(int id)
            {
                var producto = await _context.Productos.FindAsync(id);
    
                _context.Productos.Remove(producto);
                await _context.SaveChangesAsync();
    
                producto = await _context.Productos.AsQueryable<Producto>().LastOrDefaultAsync();
    
                if (producto == null)
                {
                    producto = new Producto();
                }
    
                return producto;
            }
    

    The responseText:

    api/Productos/5:1 Failed to load resource: the server responded with a status of 500 ()
    api/Productos/5:1 Failed to load resource: the server responded with a status of 500 ()
    config:1773 System.ArgumentNullException: Value cannot be null. (Parameter 'entity')
       at Microsoft.EntityFrameworkCore.Utilities.Check.NotNull[T](T value, String parameterName)
       at Microsoft.EntityFrameworkCore.DbContext.Remove[TEntity](TEntity entity)
       at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.Remove(TEntity entity)
       at Tienda.Controllers.ProductosController.DeleteProducto(Int32 id) in D:\Documents\Visual Studio 2019\Projects\DesarrolloWeb\Tienda\Controllers\ProductosController.cs:line 117
       at lambda_method(Closure , Object )
       at Microsoft.Extensions.Internal.ObjectMethodExecutorAwaitable.Awaiter.GetResult()
       at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
       at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
       at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
       at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
       at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
       at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
       at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
       at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
       at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
       at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
       at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
       at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
       at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
       at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
    
    HEADERS
    =======
    Accept: */*
    Accept-Encoding: gzip, deflate, br
    Accept-Language: es,es-ES;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6
    Cache-Control: no-cache
    Connection: close
    Cookie: UltIdProducto=5; .AspNetCore.Antiforgery.kpkyKqXb3cQ=CfDJ8Pd8cRKWTcdNqVzVVvXtmByBhwBwC1e5j0Nm0rpHDkviQKFjLqKMj_BhXoTj-XjON9dgl4876nDaJe4gG7cma1mwETlF2R6xda8N6JjdrSqDowe-rRhtTfv5Iz62QCn2jX5AlF0hbiXJuzHh9tsxvdk
    Host: localhost:44374
    Pragma: no-cache
    Referer: https://localhost:44374/config
    User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36 Edg/83.0.478.64
    x-requested-with: XMLHttpRequest
    origin: https://localhost:44374
    sec-fetch-site: same-origin
    sec-fetch-mode: cors
    sec-fetch-dest: empty
    
    Wednesday, July 15, 2020 11:52 AM

All replies

  • User753101303 posted

    Hi,

    So Remove complains about being called with a null entity.

    FindAsync can return null if the id key doesn't match. As it seems to always happen, more likely you are not passing the id correctly. Check this is the expected value rather than maybe 0 ?

    If it's rare (or once you fixed the initial issue) you still my want to handle that in your code, for example in case someone would try to delete an entity that was just deleted by someone else.

    Wednesday, July 15, 2020 12:02 PM
  • User-217098811 posted

    Hi,FedericoLuna

    From the error returned, you should not have the correct id.

    Try this code:

            [HttpPost, ActionName("Delete")]
    	public async Task<ActionResult<Producto>> DeleteProducto(int id)
           
    { var producto = await _context.Productos.FindAsync(id); _context.Productos.Remove(producto); await _context.SaveChangesAsync(); producto = await _context.Productos.AsQueryable<Producto>().LastOrDefaultAsync(); if (producto == null) { producto = new Producto(); } return producto; } }

    I would like to ask if you are using EFCore 3.X.If it is, then your LastOrDefaultAsync() method will not work properly.

    This is a new one after EFCore3.0 Features, you can take a look at this:

    https://docs.microsoft.com/en-us/ef/core/what-is-new/ef-core-3.0/breaking-changes?view=aspnetcore-1.1#linq-queries-are-no-longer-evaluated-on-the-client

    Hope this can help you 

    Best Regards

    yinqiu

    Thursday, July 16, 2020 2:51 AM