SaveChangesAsync不更新数据库表中的值

时间:2015-05-22 05:17:30

标签: c# asp.net-mvc entity-framework async-await

这是我的表:统计

Id,Depth,RefreshCounter

样本记录:

Id    Depth      RefreshCounter
 1     1           1
 2     1           0
 3     1           0
 4     1           0

现在我需要做的是每当我刷新页面时,我需要在深度为1的数据库表中将此refreshcounter值增加1

我在加载浏览页面时调用此方法:

@Html.Action("IncrementRefreshcounter", "Statistics", new { id = 1})  //for eg:1,2,3,4

这是我的代码:

    [ChildActionOnly]
    public ActionResult IncrementRefreshcounter(int id)
       {
         using ( var context = new MyDBContext())
         {
//at each page refresh i would be passing different id to my controller from view.for eg 1,2,3,4
         var data=context.Statistics.where(x=>x.Depth==1 && r.Id==id).FirstorDefualt();
             context.RefreshCounter++;//Increment here RefreshCounter.
             context.SaveChangesAsync();
             return PartialView("xxx")
            }
        }

我正在调用此方法当我的View Loads.Problem是我第一次运行我的应用程序并调用此方法时,它成功更新了RefreshCounter 1,但之后每当我刷新页面并调用此方法时,它从未更新任何RefreshCounter Depth = 1的记录。

在我的示例记录中,您可以看到Id 1 with Depth 1具有值为1的刷新计数器,因为这是我第一次运行我的应用程序并且它已成功更新该值但在此之后它永远不会更新任何值例如:Id 2 Depth 1

它只增加了一次RefreshCounter,但之后它永远不会增加该变量。

有人能告诉我问题是什么 SaveChangesAsync ??

2 个答案:

答案 0 :(得分:12)

您必须等待保存,否则方法将继续,并且在保存更改之前您的上下文将超出范围。你也必须使方法异步。

public **async** Task<ActionResult> IncrementRefreshcounter(int id)
       {
         using ( var context = new MyDBContext())
         {
//at each page refresh i would be passing different id to my controller from view.for eg 1,2,3,4
         var data=context.Statistics.where(x=>x.Depth==1 && r.Id==id).FirstorDefualt();
             context.RefreshCounter++;//Increment here RefreshCounter.
             await context.SaveChangesAsync();
            }
        }

答案 1 :(得分:7)

试试这个:

   public async Task<ActionResult> IncrementRefreshcounter(int id)
   {
     using ( var context = new MyDBContext())
     {
//at each page refresh i would be passing different id to my controller from view.for eg 1,2,3,4
     var data=context.Statistics.where(x=>x.Depth==1 && r.Id==id).FirstorDefualt();
         context.RefreshCounter++;//Increment here RefreshCounter.
         await context.SaveChangesAsync();
        }
    }

SaveChanges将在当前线程上执行并在等待查询完成时阻塞线程,防止线程执行其他工作,即使线程只是坐在那里等待IO。

SaveChangesAsync将启动IO命令,然后在IO正在进行时释放请求线程以执行其他工作。 IO完成后,将在捕获的同步上下文上执行该方法的其余部分。

因此,对于使用asyncrhonous API进行IO绑定工作的Web服务器,您可以使用更少的线程提供更多请求,从而使您的应用程序更具可伸缩性,并且它将使用更少的内存以及每个线程默认具有1MB的堆栈空间

同步工作与SaveChanges方法类似。在保存更改之前,方法调用不会返回。

异步工作类似于SaveChangesAsync,方法调用启动操作并返回Task,以便您可以跟踪它。然后,一段时间后,更改将保存在后台,同时您可以使用返回的Task来跟踪操作。