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

 

代码报错:

 

 

复制代码
 #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 删除教师
View Code
复制代码

 

 

解决方案:

将方法的每个数据库操作都await,如下图:

 

 

 

 

有关如何避免 DbContext 线程问题的详细信息,请参考链接:https://docs.microsoft.com/zh-cn/ef/core/dbcontext-configuration/#avoiding-dbcontext-threading-issues

 

posted @   lanrenka  阅读(2129)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 上周热点回顾(3.3-3.9)
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
点击右上角即可分享
微信分享提示