Trying to delete user:

public async Task<ActionResult> Delete(string id) { ApplicationUser user = await userManager.FindByIdAsync(id); if (user != null) { IdentityResult result = await userManager.DeleteAsync(user); if (result.Succeeded) { return RedirectToAction("Index"); } else { TempData["Error"] = "Error!"; return RedirectToAction("Index"); } } TempData["Error"] = "Error!"; return RedirectToAction("Index"); } 

User is not deleted. An error occurs:

System.Data.Entity.Infrastructure.DbUpdateException : See the inner exception for details. ---> System.Data.Entity.Core.UpdateException : See the inner exception for details. ---> System.Data.SqlClient.SqlException: The DELETE statement conflicted with the REFERENCE constraint "FK_dbo.ClientProfiles_dbo.AspNetUsers_Id". The conflict occurred in the database "Schedule", table "dbo.ClientProfiles", column 'Id'. The statement has been terminated.

I tried to delete the role first, and then the user himself, but the error still occurs. How to fix it?

  • one
    You will have to change the requirements for the foreign key "FK_dbo.ClientProfiles_dbo.AspNetUsers_Id", apparently, to cascade deletion. In general, deleting system users is wrong practice, you cannot delete users, you need to make them inactive (add the IsActive field to the users table), you delete the user, but what happens to his records and activities in the rest of the database? Also delete? And then recalculate the indexes? - Bulson
  • @Bulson, thank you very much for the comment! Instead of deleting, I make users inactive - Nikita

1 answer 1

As written in the comments:

deleting system users is wrong practice

So instead of deleting, I make users inactive.

In UserManager you need to register:

 UserManager.UserLockoutEnabledByDefault = true; //Ρ€Π°Π·Ρ€Π΅ΡˆΠ°Π΅Ρ‚ Π±Π»ΠΎΠΊΠΈΡ€ΠΎΠ²ΠΊΡƒ ΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚Π΅Π»Π΅ΠΉ UserManager.DefaultAccountLockoutTimeSpan = DateTime.Now.AddYears(100).TimeOfDay; //врСмя Π±Π»ΠΎΠΊΠΈΡ€ΠΎΠ²ΠΊΠΈ 

Further, when I want to block a user:

 public async Task<ActionResult> LockOut(string id) { ApplicationUser user = await userManager.FindByIdAsync(id); if (user != null) { user.LockoutEnabled = true; await userManager.UpdateAsync(user); } return RedirectToAction("Index"); }