这是我的表:统计
Id,Depth,RefreshCounter
示例记录:
Id Depth RefreshCounter
1 1 1
2 1 0
3 1 0
4 1 0
现在我需要做的是,每当我刷新页面时,我需要在深度为 1 的数据库表中将此 refreshcounter 值递增 1。
我在加载我的 View 页面时调用此方法:
@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 加载时调用此方法。问题是当我第一次运行我的应用程序并调用此方法时,它成功地将 RefreshCounter 更新为 1,但之后每当我刷新我的页面并调用此方法时,它从未更新任何 RefreshCounter Depth=1 的记录。
在我的示例记录中,您可以看到深度为 1 的 ID 1 的刷新计数器值为 1,因为这是我第一次运行我的应用程序并且它已成功更新该值,但之后它永远不会更新任何值例如:Id 2 深度 1
它只递增 1 次 RefreshCounter 但之后它永远不会递增该变量。
谁能告诉我 SaveChangesAsync 是什么问题??
最佳答案
您必须等待保存,否则该方法将继续并且您的上下文将在保存更改之前超出范围。您还必须使该方法异步。
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();
}
}
关于c# - SaveChangesAsync 不更新数据库表中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30388844/