I created several users in the system. Adding goes without problems, but editing causes an error

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

[HttpPost] [ValidateAntiForgeryToken] public IActionResult Edit(ApplicationUser applicationUser) { IdentityUser user; if (ModelState.IsValid && (user = _context.Users.SingleOrDefault(x => x.Id == applicationUser.Id)) != null) { user.UserName = applicationUser.UserName; //_context.Update(applicationUser); _context.SaveChanges(); return RedirectToAction("Index"); } return View(applicationUser); } 
  • create a new asp.net-mvc application and add the following package to the nuget package manager: Microsoft ASP.NET Identity Samples 2.1.0-alpha1 , so that the package is available in the list, do not forget to include Include prerelease , then study the example as work with asp.net-identity-2 - Bald
  • I just use this demo application. There is no ability to edit user data - Rajab
  • pay close attention to UserAdminController in particular. Edit method edits user - Bald
  • I have Identity 3. I hope there’s no difference? - Radzhab
  • I find it hard to answer you, I use asp.net-mvc-identity-2 . look at the UserManager methods in your version, you’ll have to wrap them in the controller inside your asp.net-mvc application - Bald

1 answer 1

This error indicates that the previous request is not completed in the same context and is trying to make another request. If possible, use a short context lifetime.

 using(var context = new AppContext()){ //..действия с контекстом.../// } 

It is also possible that a query was previously used in the context, the result of which is set and which is not completed by the .ToList() method, which executes the query.