DbUpdateConcurrencyException: Database operation expected to affect 1 row(s) but actually affected 0 row(s). Data may have been modified or deleted since entities were loaded.

The .NET Core Entity framework makes database access easy. When you auto-generate a Razor page in a .NET web application to edit a data row, the scaffolding places controls on the page for every column.

There are columns in most of the tables that we don’t want to display or edit, like keys, checksums, password hashes. If column¬†values are missing during database update, the error is thrown:

A database operation failed while processing the request.
DbUpdateConcurrencyException: Database operation expected to affect 1 row(s) but actually affected 0 row(s). Data may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=527962 for information on understanding and handling optimistic concurrency exceptions.

When the edit page is displayed, all values of the row are passed to the page in the Model. When the user clicks the Save button the model is sent back to the server, and the¬†OnPostAsync() method saves the values to the database. The values that we don’t display or store otherwise on the web page are not retained in the browser, and not passed back to the server. To keep the not displayed values, add hidden attributes to the page. The primary key of the row is automatically added, and based on that create hidden attributes for the rest of the not displayed columns.

 <form method="post">
 <div asp-validation-summary="ModelOnly" class="text-danger"></div>
 <input type="hidden" asp-for="ApplicationUser.Id" />
 <input type="hidden" asp-for="ApplicationUser.AccessFailedCount" />
 <input type="hidden" asp-for="ApplicationUser.ConcurrencyStamp" />
 <input type="hidden" asp-for="ApplicationUser.NormalizedEmail" />
 <input type="hidden" asp-for="ApplicationUser.NormalizedUserName" />
 <input type="hidden" asp-for="ApplicationUser.PasswordHash" />
 <input type="hidden" asp-for="ApplicationUser.SecurityStamp" />
 <input type="hidden" asp-for="ApplicationUser.UserName" />