【问题标题】:InvalidOperationException: An operation is already in progressInvalidOperationException:操作已在进行中
【发布时间】:2017-02-03 23:11:50
【问题描述】:

我正在使用 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");
}

【问题讨论】:

    标签: c# asp.net entity-framework razorengine


    【解决方案1】:

    您可以尝试将 AsEnumerable 替换为 ToList 吗?

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

    【讨论】:

    • 因为 enumerables 不会将所有数据加载到内存中,而是在您通过 _context 枚举它们并在循环内再次使用 _context 删除正在枚举的同一实体上的数据时从数据库中获取数据。调用 .ToList() 会首先加载拍卖数据的副本,因此 _context 只需对拍卖实体执行单个操作,即移除。
    • AsEnumerable 是一个延迟操作,您在该步骤中再次在数据库上下文中执行某些操作。这就是您遇到该错误的原因。
    • 这不是一个好的答案,因为它只是隐藏了潜在的问题。例如,如果有一百万条记录,在对它们进行任何操作之前将它们全部加载到内存中。作为一个任务,你正在做什么,而当这个任务正在处理时,另一个任务需要在上下文中执行一些事情?在我看来,我们需要用于依赖注入的 AddDbContext 不起作用,因为在许多这样的场景中,多个后台进程都需要来自数据存储的数据。我没有这个问题的答案,因此我的搜索出现了这个错误。
    【解决方案2】:

    我将MultipleActiveResultSets=True 添加到我的 sql server 连接字符串中,这修复了异常。无需进行其他更改。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-05
      • 2021-11-25
      • 2017-10-28
      • 1970-01-01
      • 2011-01-22
      • 2017-01-28
      • 1970-01-01
      相关资源
      最近更新 更多