SaveChangesAsync不更新数据库表中的值
这是我的表: 统计数据
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 = 1。
在我的示例记录中,您可以看到Id 1 with Depth 1具有值为1的刷新计数器,因为这是我第一次运行我的应用程序并且它已成功更新该值但在此之后它永远不会更新任何值,例如: Id 2深度1
它只增加了一次RefreshCounter但在此之后它永远不会增加该变量。
谁能告诉我什么问题是SaveChangesAsync ?
您必须等待保存,否则方法将继续,并且在保存更改之前,您的上下文将超出范围。 您还必须使该方法异步。
public **async** Task 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(); } }
试试这个:
public async Task 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
来跟踪操作。