In my ASP.NET Web API application, I get the following error in one of my actions, at the line below:
var dateExists = await _unitOfWork.GetRepository<Booking>().All()
.AnyAsync(b => b.User.UserName == booking.User.UserName && b.Date == model.Date);
Here's the error:
A second operation started on this context before a previous asynchronous operation completed. Use 'await' to ensure that any asynchronous operations have completed before calling another method on this context. Any instance members are not guaranteed to be thread safe.
But, as you can see, I am using await
. I'm also using await
on all the other async operations in the action. Then, what might be the problem?
Edit:
Here's my entire action:
[HttpPut]
[Route("Update")]
public async Task<IHttpActionResult> Put(BookingEditBindingModel model)
{
if (!ModelState.IsValid)
{
// Return a bad request response if the model state is invalid...
return BadRequest(ModelState);
}
try
{
var booking = await _unitOfWork.GetRepository<Booking>().FindAsync(model.BookingId);
if (booking == null)
{
return NotFound();
}
// Only Admin is allowed to update other users' data...
if (!User.IsInRole("Admin") && booking.User.UserName != User.Identity.Name)
{
return Unauthorized();
}
// There can only be one entry per date/user.
if (model.Date != booking.Date)
{
var dateExists = await _unitOfWork.GetRepository<Booking>().All()
.AnyAsync(b => b.User.UserName == booking.User.UserName && b.Date == model.Date);
if (dateExists)
{
ModelState.AddModelError("Date", "Data already exists for this date.");
return BadRequest(ModelState);
}
}
booking.Date = model.Date;
// Change other properties...
await _unitOfWork.SaveAsync();
return Ok();
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
Update:
I disabled lazy loading, but I still had a problem. It looks like, as other people had guessed, the issue was with booking.User
, because the FindAsync()
in the first query does not include the User
. I replaced the first query with the one below, and the issue was resolved.
var booking = await _unitOfWork.GetRepository<Booking>().All()
.Include(b => b.User)
.SingleOrDefaultAsync(b => b.BookingId == model.BookingId);