簡體   English   中英

InvalidOperationException:操作已在進行中

[英]InvalidOperationException: An operation is already in progress

我正在使用Asp.net核心Razor引擎實體框架。 我一直在得到上面的錯誤,從我讀到的錯誤來看,它是指已經用於操作的數據庫。 我不確定為什么會這樣。 是因為它處於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();

我在SQL Server連接字符串中添加了MultipleActiveResultSets=True從而解決了該異常。 無需其他更改。

這為我修復了異步方法,后台任務和IQueryable循環。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM