Home > OS >  DbUpdateConcurrencyException: Database operation expected to affect 1 row(s) but actually affected 0
DbUpdateConcurrencyException: Database operation expected to affect 1 row(s) but actually affected 0

Time:03-15

I am using EF Core 5.0 Version
Asp.net core razor page (.Net 5.0) SQL 2019

The Student Table contains RowVersion(TimeStamp not null) I generated the dbcontext scaffold and the modelbuilder is

 entity.Property(e => e.RowVersion)
                .IsRequired()
                .IsRowVersion()
                .IsConcurrencyToken(); 

Whenever i update the student name I am getting the error

  DbUpdateConcurrencyException: Database operation expected to affect 1 row(s) but actually affected 0 row(s). 

I tried replacing the modelbuilder with

  entity.Property(e => e.RowVersion)
                    .IsRowVersion()
                

The code that does the update:

 public async Task<IActionResult> OnPostAsync()
    {
        if (!ModelState.IsValid)
        {
            return Page();
        }

        _context.Attach(Student).State = EntityState.Modified;

        try
        {
           
            await _context.SaveChangesAsync(true);
        }
        catch (DbUpdateConcurrencyException)
        {
            if (!StudentExists(Student.StudentId))
            {
                return NotFound();
            }
            else
            {
                throw;
            }
        }

        return RedirectToPage("./Index");
    }

but i could not get past the error. The problem is only with the TimeStamp datatype of sql-server.

CodePudding user response:

I figured out after 8 hours, that the RowVersion was missing in the update command itself since it was not passed on the postback.

I included a hidden field in the view page like this for Rowversion that solved the problem.

        <input type="hidden" asp-for="Student.StudentId" />
        <input type="hidden" asp-for="Student.RowVersion" />
  • Related