ASP.Net MVC foreach循环不持久化更改

本文关键字:持久化 不持久 循环 Net MVC foreach ASP | 更新日期: 2023-09-27 18:16:06

我有一个我认为是简单的情况-但我已经被困了一段时间了。

我只是查询数据库,并将结果放入视图模型:CallVM -该部分工作良好。

然后我想做的是,它循环通过QueueByTeam对象,并更新其中一个属性-然而,"循环"部分,不保存对QueueByTeam对象的更改,所以当我将对象返回给视图时,我的更新被忽略了:

  var QueueByTeam = db.Calls.Where(x => x.assignedteam == id)
         .Select(call => new CallVM
          {
              customer = call.customer,
              nexttargetdate = call.nexttargetdate
              owner = "";
          });

        foreach (var calls in QueueByTeam)
        {
            calls.owner = "--------";
        }
        // at this point, QueueByTeam has ignored changing the `owner` field to "-------"           
        return View(QueueByTeam.ToList());

在返回到视图之前,我需要在foreach循环后做一些事情来保存更改吗?

谢谢,马克

ASP.Net MVC foreach循环不持久化更改

将代码改为:

 var QueueByTeam = db.Calls.Where(x => x.assignedteam == id)
     .Select(call => new CallVM
      {
          customer = call.customer,
          nexttargetdate = call.nexttargetdate
          owner = "";
      })
      .ToList();

    foreach (var calls in QueueByTeam)
    {
        calls.owner = "--------";
    }
    // at this point, QueueByTeam has ignored changing the `owner` field to "-------"           
    return View(QueueByTeam);

。在尝试更改数据之前,将ToList()直接放在Select之后。这将强制立即运行数据库查询,并将结果存储在列表中。

从它的外观来看,每次你查询你的QueuesByTeam时,它都在请求数据库,因此丢失了你的更改。

作为旁注,如果更改只是将所有者设置为"-----",则可以将其直接放入原始select语句中,而不是使用单独的for循环。