InvalidOperationException:操作已在进行中

InvalidOperationException: An operation is already in progress

我正在使用 Asp.net 核心 Razor 引擎 Entity Framework。我不断收到上面的错误,从我读到的内容来看,它指的是数据库已经被用于操作。我不确定为什么会这样。是因为它在 foreach 循环中吗?解决方法是什么?这是我的代码

[HttpGet]
[Route("currentSession")]
public IActionResult CurrentSession()
{

    var id = HttpContext.Session.GetInt32("Id");
    if(id != null)
    {
        var user = _context.User.FirstOrDefault(x => x.Id == id);
         ViewBag.User = user;
         ViewBag.User_Id = id;
         ViewBag.Auction = _context.Auction.AsEnumerable();
         foreach(var item in ViewBag.Auction)
         {
             if(item.End_Date < DateTime.Now)
             {
                 var seller_id = (int)item.Id_Of_Seller;
                 var seller = _context.User.FirstOrDefault(x => x.Id == seller_id); //this is the line that causes the error in the title
                 var bidder_id = (int)item.Id_Highest_Bid;
                 var buyer = _context.User.FirstOrDefault(x => x.Id == bidder_id); //this line also causes the same error
                 buyer.Wallet -= item.Bid;
                 seller.Wallet += item.Bid;

                _context.Auction.Remove(item);
                _context.SaveChanges();
             }
         }
         return View("Home");
    } 
    return RedirectToAction("LoginPage");
}

您可以尝试用 ToList 替换 AsEnumerable 吗?

         ViewBag.Auction = _context.Auction.ToList();

我将 MultipleActiveResultSets=True 添加到我的 sql 服务器连接字符串中,这修复了异常。不需要其他更改。

这为我修复了异步方法、后台任务和 IQueryable 循环。