加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – SaveChangesAsync不更新数据库表中的值

发布时间:2020-12-15 18:32:59 所属栏目:百科 来源:网络整理
导读:这是我的表:统计数据 Id,Depth,RefreshCounter 样本记录: Id Depth RefreshCounter 1 1 1 2 1 0 3 1 0 4 1 0 现在我需要做的是每当我刷新页面时,我需要在深度为1的数据库表中将此refreshcounter值增加1. 我在加载浏览页面时调用此方法: @Html.Action("Inc
这是我的表:统计数据
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,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

它只递增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,4
         var data=context.Statistics.where(x=>x.Depth==1 && r.Id==id).FirstorDefualt();
             context.RefreshCounter++;//Increment here RefreshCounter.
             await context.SaveChangesAsync();
            }
        }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读