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.