Receiving a Cannot access a disposed context instance. error when trying to execute a _context.SaveChangesAsync command

Matthew Henderson 0 Reputation points
2023-04-19T18:51:30.3266667+00:00

This error occurs in a controller when trying to add a new customer. I have attached the source files in hope that someone can help. Thank you. code segment in CustomerController:

if (_context != null && _context.Customers != null)
                {
                    _context.Add(newCust);  //this executes without error
                    await _context.SaveChangesAsync(); //this is where the error occurs which makes no sense to get a "disposed" error message.
                }

DataContext.txt Program(Server).txt CustomerClass.txt CustomerPage(razor component).txt CustomersService.txt CustomerController.txt

Developer technologies | .NET | Entity Framework Core
Developer technologies | .NET | Blazor
Windows for business | Windows Client for IT Pros | User experience | Other
{count} votes

1 answer

Sort by: Most helpful
  1. Anonymous
    2023-04-20T01:33:03.0266667+00:00

    Hi Matthew Henderson,

    Update:

    As AgaveJoe said, Never return void from an async method. Avoid Async Void

    [HttpPost]
            public async Task SaveCustomerAsync([FromBody] CustomerRequest request)
    

    According to your CustomerController codes, we found you call the asynchronous SaveChangesAsync and the synchronous SaveChanges methods on the same DbContext instance inside the SaveCustomerAsync method. When you call the synchronous SaveChanges method, it will block until the changes are saved to the database, and in the process, it could dispose of the DbContext instance. If that happens, calling the asynchronous SaveChangesAsync method on the same disposed DbContext instance will result in the "Cannot access a disposed context instance" error. I suggest you could modify it to all using the SaveChangesAsync method. Like below:

            [HttpPost]
            public async void SaveCustomerAsync([FromBody] CustomerRequest request)
            {
                int id = request.Id;
                Customer? customer = request.customer;
    
    
        if (id == 0)
        {
            var newCust = new Customer()
            {
                Name = customer.Name,
                Address1 = customer.Address1,
                Address2 = customer.Address2,
                City = customer.City,
                State = customer.State,
                ZipCode = customer.ZipCode,
                Phone = customer.Phone
            };
    
            if (_context != null && _context.Customers != null)
            {
                _context.Add(newCust);
                await _context.SaveChangesAsync();
            }
        }
        else
        {
            if (_context != null && _context.Customers != null)
            {
                var updateCust = _context.Customers.FirstOrDefault(c => c.Id == id);
                if (updateCust != null)
                {
                    updateCust.Name = customer.Name;
                    updateCust.Address1 = customer.Address1;
                    updateCust.Address2 = customer.Address2;
                    updateCust.City = customer.City;
                    updateCust.State = customer.State;
                    updateCust.ZipCode = customer.ZipCode;
                    updateCust.Phone = customer.Phone;
    
                    _context.Customers.Update(updateCust);
                    await _context.SaveChangesAsync(); // Use the asynchronous method here
                }
    
            }
        }
    }
    

    }

    }
    
    

    ***************************************************** 
    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.