SaveChangesAsync not updating value in database table

This is my Table:Statistics

Id,Depth,RefreshCounter

Sample Records:

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

Now what i need to do is whenever i am refreshing the page i need to increment this refreshcounter value by 1 in Database table with Depth 1.

I am calling this method like this on load of my view page:

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

Here is my code which does this:

[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") } }

I am calling this method when my View Loads.Problem is when i run my Application first time and calling this method it successfully updated RefreshCounter by 1 but after that whenever i refresh my page and calling this method it never updated RefreshCounter for any records with Depth=1.

In my sample Records you can see that Id 1 with Depth 1 have refresh counter with value 1 because it was the first time when i have run my application and it has successfully updated that value but after that it is never updating any value for eg:Id 2 Depth 1

It is incrementing only 1 time RefreshCounter but after that it never increments that variable.

Can anybody tell me what the problem is SaveChangesAsync ??

--------------Solutions-------------

You have to await the save otherwise the method will continue and your context would go out of scope before saving changes. You have to make the method asynchronous, too.

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();
}
}

Try this:

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 will execute on the current thread and block the thread while waiting for the query to complete, preventing the thread from doing other work, even though the thread is just sitting there waiting for IO.

SaveChangesAsync will kick off the IO command and then free up the request thread to do other work while the IO is in progress. Once the IO completes, the rest of the method is executed on the captured synchronization context.

So for a web server using asyncrhonous APIs for IO bound work enables you to serve more requests with fewer threads and thus makes your application more scalable and it will use much less memory as well as each thread has 1MB of stack space by default.

Synchronous work is like the SaveChanges method. The method call does not return until the changes are saved.

Asynchronous work is like SaveChangesAsync, the method call initiates the operation and returns a Task so you can keep track of it. The changes are then saved in the background some time later and in the mean time you can use the returned Task to keep track of the operation.

Category:c# Time:2018-08-06 Views:0

Related post

  • It's not saving value into database table, why? 2012-01-14

    def register(request): flag = True possible = '0123456789abcdefghijklmnopqrstuvwxyz' token = '' length = 10 i = 0 current_datetime = datetime.datetime.now() user = UsersModelForm() if request.method == 'POST': userf = UsersModelForm(request.POST) use

  • Update values in one table from three other joined tables in H2 (and DB2) 2012-03-02

    I'm trying to achieve something like described here in H2: Update with inner join? update tlegacy lca set lca.pr_dato = ca.calc_holdings_date ... from tca ca inner join tdd dd on ... and I get Error: Column "CA.CALC_HOLDINGS_DATE" not found in H2. Th

  • Updating values to a table based on another table slow 2010-11-09

    I wanted to know why my select statement is orders of magnitude faster than my update statement when updating values from one table to another as opposed to selecting values from one table to another. The example below illustrates my problem, I can r

  • Updating Values of a table from same table without using a select query 2011-11-18

    My Requirement Updating Values of a table from same table without using a select query this query won't effect any rows. My aim : Update val2 of #table where slno=1 with the value of val2 of slno=2 Is there any other way without doing this method Dec

  • F9 does not update field codes or table of contents 2014-12-26

    In a Word 2007, when I access one specific template (developed in 2003 or earlier, but now has a dotm extension), or a document based on this template, I enjoy all features of this template (styles, autotexts, macros, toolbar), except for one thing:

  • cakephp not saving update value to related table, but no errors 2010-05-05

    Update order function finds all orderlines of current order. Loops through subtracting quantity ordered from stock level and holding new stock level value in $newstock. All good. But won't save. Echoes "success" and the correct value but the database

  • ASP.NET MVC 2 UpdateModel() is not updating values in memory or database 2010-05-29

    I am new to MVC, and so am working through the NerdDinner tutorial, here. In particular, I'm running into problems with the use of the UpdateModel method, which is explained in the part five of that tutorial. The problem is, when I try to edit the va

  • Values not updating correctly in database after being operated on in a loop 2011-03-18

    I have the following code: Imports System.Data Imports System.Data.OleDb Partial Class Dummy Inherits System.Web.UI.Page Dim r As OleDbDataReader Dim con As OleDb.OleDbConnection Dim cmd As OleDbCommand Dim cmd1 As OleDbCommand Dim prev_ob As New Lis

  • How do I get a windows C# control to automatically update if the database table updates/inserts? 2010-11-22

    I have a listView WinForms-C# that I've binded to a database (MySQL) table but I can't seem to figure out how to have the listView automatically display the results when changes are made to the database table (update/insert) without the user having t

  • Avoid insert 'null' values to database table via JPA 2010-12-22

    im starting with JPA2 and feel quite comfortbale so far. But I have a problem when persisting Entities with null property values for NON NULL database fields with default value. I would like to be able to leave the entity property null and let the da

  • Hibernate not matching values in database 2011-08-01

    I have a table called SecurityContacts and another table called Contacts. The association between them is ManyToOne. SecurityContacts has columns for both an AgentContact and an AuditContact, which are two different types of contacts. It also has a c

  • Custom button in DetailsView updates value in Database 2011-08-13

    I'm trying to practice and started with small game. Users can register and so on. Now I have no idea how to perform user to "work", I have GridView and DetailsView, in GridView user selects company and it displays in DetailsView. In DetailsView I hav

  • Entity Framework not updating data in database with update 2011-10-04

    I am trying to insert/update data into a table using Entity Framework 4.1 from an Edit action in my MVC3 controller with the following code: [HttpPost] public ActionResult Edit(UserDetailsForm form) { try { if (ModelState.IsValid) { UserProfile up =

  • Default column value in database table is null after persisting a entity 2011-11-22

    From the image above you can see a column in the MySQL database (table Question) where I have a column that has a default value of 'Approved'. However if I make a new Question instance, set values on the object but not the status property it persist

  • why it is not updating url in database 2012-03-07

    I have a page named ques.php. If the user's answer is correct he will be directed to next ques1.php. The answer posted by the user is checked by check.php and if it is correct I want to store the new URL (ques1.php) in the users account in the databa

  • How can I update values in MySQL table If other values are duplicates? 2012-03-13

    I have table with following structure : TBL1 COL1 COL2 COL2 ---- ---- ---- A B 1 B C 3 A C 11 A D 13 B D 10 How can I update col3 If values in col1 are duplicates ? I want the values ​​in col3 be updated with the largest found. Тhe resulting table to

  • Problem with "This Recordset is not Updatable" in a temporary table Query 2012-03-04

    Can anyone help me? I have a database where I have created a temporary table. I am trying to make it so that I can update the production column and this will then increase the predictive stock column. Fields are: [Autonumber] [Field1] [Weekly Qty] [R

  • Access 2007 problem: Combo box stores the source ID and not the value into the table 2014-03-02

    I have two combo boxes, Topic and Subtopic, and I use the following code to set the rowsource for the Subtopic based on the Topic that is selected: Private Sub Topic_AfterUpdate() Me.Subtopic.RowSource = "SELECT [Topics].[Subtopic], [Topics].[Topic],

  • ACCESS 2002 forms not saving data to database table 2015-01-06

    I recently made a change to one form in an existing ACCESS application. I'm using the ACCESS version that came on my computer with Office XP (I believe it is ACCESS 2002). There was pre-existing data in the database table before my update. During tes

Copyright (C) pcaskme.com, All Rights Reserved.

processed in 0.942 (s). 13 q(s)