Error text: InvalidOperationException: A second operation was started on this context instance before a previous operation completed. This is usually caused by different threads concurrently using the same instance of DbContext. For more information on how to avoid threading issues with DbContext, see https://go.microsoft.com/fwlink/?linkid=2097913. Code:
DI
builder.Services.AddDbContext<MedicardDbContext>(options =>
{
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
});
builder.Services.AddScoped(typeof(IGenericRepository<>), typeof(GenericRepository<>));
builder.Services.AddTransient<IUnitOfWork, UnitOfWork>();
Controller:
public async Task<IActionResult> AllChats()
{
var currentUser = await _userManager.GetUserAsync(User);
var allUsers = await _chatService.GetAllTargetUsersBasedOnRole(currentUser);
var chatsViewModel = await _chatService.GetListChats(allUsers, currentUser);
return View(chatsViewModel);
}
ChatService:
public async Task<List<ChatViewModel>> GetListChats(List<User> allUsers, User currentUser)
{
var chatsViewModel = new List<ChatViewModel>();
foreach (var targetUser in allUsers)
{
var chat = new ChatViewModel
{
UserName = targetUser.UserName,
FullName = targetUser.ToString(),
};
var picture = await GetPictureForChat(targetUser);
if (picture == null)
{
var doctor = _unitOfWork.GenericRepository<Doctor>().GetAll(doctor => doctor.UserId == targetUser.Id).FirstOrDefault();
chat.Picture = doctor.DoctorPicture;
}
else
{
chat.Picture = picture;
}
chatsViewModel.Add(chat);
}
return chatsViewModel;
}
Method GetPictureForChat:
private async Task<string> GetPictureForChat(User user)
{
return await _userManager.IsInRoleAsync(user, "Admin") ? "admin.png" :
await _userManager.IsInRoleAsync(user, "Doctor") ? null : "user.png";
}
UnitOfWork:
public class UnitOfWork : IUnitOfWork, IDisposable
{
private readonly MedicardDbContext _context;
public UnitOfWork(MedicardDbContext context)
{
_context = context;
}
private bool disposed = false;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
_context.Dispose();
}
}
this.disposed = true;
}
public IGenericRepository<T> GenericRepository<T>() where T : class
{
IGenericRepository<T> repository = new GenericRepository<T>(_context);
return repository;
}
public void Save()
{
_context.SaveChanges();
}
public async Task SaveAsync()
{
await _context.SaveChangesAsync();
}
}
The error is written somewhere along these lines:
return await _userManager.IsInRoleAsync(user, "Admin") ? "admin.png" :
await _userManager.IsInRoleAsync(user, "Doctor") ? null : "user.png";
and
var picture = await GetPictureForChat(targetUser);
and
var chatsViewModel = await _chatService.GetListChats(allUsers, currentUser);
But I don't know how to solve it.