ef core报错“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.”
环境:
asp .net core 6
ef core
代码报错:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#region 删除教师 [HttpPost] public async Task<IActionResult> Delete(int id) { var teacher = _teacherRepository.FirstOrDefaultAsync(a => a.Id == id); if (teacher == null) { ViewBag.ErrorMessage = $"教师编号{id}的信息不存在,请重试。"; return View("NotFound"); } await _officeRepository.DeleteAsync(a=>a.TeacherId==teacher.Id); await _courseAssignmentRepository.DeleteAsync(a => a.TeacherID == teacher.Id); await _teacherRepository.DeleteAsync(a=>a.Id==teacher.Id); return RedirectToAction(nameof(Index)); } #endregion 删除教师
解决方案:
将方法的每个数据库操作都await,如下图:
有关如何避免 DbContext 线程问题的详细信息,请参考链接:https://docs.microsoft.com/zh-cn/ef/core/dbcontext-configuration/#avoiding-dbcontext-threading-issues