ASP.NET MVC 5 how to delete a user and its related data in Identity 2.0

Hi I'm following this article to delete a user in Identity 2.0 http://www.asp.net/mvc/tutorials/mvc-5/introduction/examining-the-details-and-delete-methods

However, I need to delete all related records in AspNetUserRoles first and then delete the user.

I found an example which is written in Identity 1.0 and some of methods used inside this example don't exist.

   // POST: /Users/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> DeleteConfirmed(string id)
        {
            if (ModelState.IsValid)
            {
                if (id == null)
                {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }

                var user = await context.Users.FindAsync(id);
                var logins = user.Logins;
                foreach (var login in logins)
                {
                    context.UserLogins.Remove(login);
                }
                var rolesForUser = await IdentityManager.Roles.GetRolesForUserAsync(id, CancellationToken.None);
                if (rolesForUser.Count() > 0)
                {

                    foreach (var item in rolesForUser)
                    {
                        var result = await IdentityManager.Roles.RemoveUserFromRoleAsync(user.Id, item.Id, CancellationToken.None);
                    }
                }
                context.Users.Remove(user);
                await context.SaveChangesAsync();
                return RedirectToAction("Index");
            }
            else
            {
                return View();
            }
        }

I cannot find IdentityManager from anywhere, and context.Users doesn't have FindAsync() method either.

Please help to figure out how to properly delete a User and its related records in Identity 2.0

Thanks.

I think the classes you're looking for are the UserManager and the RoleManager. In my opinion they are the better way instead of going against the context directly.

The UserManager defines a method RemoveFromRoleAsync which gives you the ability to remove the user (identified by his key) from a given role. It also defines several Find methods, such as FindAsync, FindByIdAsync, FindByNameAsync, or FindByEmailAsync. They all can be used to retrieve a user. To delete a user you should use the DeleteAsync method which accepts a user object as a parameter. To get the roles a user is member of Identity gives you the GetRolesAsync method where you pass in the ID of the user. Also I see that you're trying to remove a login from a user. For this purpose you should use the RemoveLoginAsync method.

All in all your code would look similar to the following one:

// POST: /Users/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> DeleteConfirmed(string id)
{
  if (ModelState.IsValid)
  {
    if (id == null)
    {
      return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }

    var user = await _userManager.FindByIdAsync(id);
    var logins = user.Logins;
    var rolesForUser = await _userManager.GetRolesAsync(id);

    using (var transaction = context.Database.BeginTransaction())
    {
      foreach (var login in logins.ToList())
      {
        await _userManager.RemoveLoginAsync(login.UserId, new UserLoginInfo(login.LoginProvider, login.ProviderKey));
      }

      if (rolesForUser.Count() > 0)
      {
        foreach (var item in rolesForUser.ToList())
        {
          // item should be the name of the role
          var result = await _userManager.RemoveFromRoleAsync(user.Id, item);
        }
      }

      await _userManager.DeleteAsync(user);
      transaction.Commit();
    }

    return RedirectToAction("Index");
  }
  else
  {
    return View();
  }
}

You'll need to adjust this snippet to your needs, because I don't have an idea how your IdentityUser implementation looks like. Remember to declare the UserManager as needed. An example how you could do this can be found when you create a new project in Visual Studio using Individual Accounts.

Add, download, and delete user data to Identity in an ASP.NET Core , With my ASP.NET Core Identity system set up I am now ready to use it. Here I will do the CRUD Operations for Creating, Reading, Updating and  Mark the custom user data model with the PersonalDataAttribute attribute so it's automatically available for download and deletion. Making the data able to be downloaded and deleted helps meet GDPR requirements. The project sample is created from a Razor Pages web app, but the instructions are similar for a ASP.NET Core MVC web app.

How to Create, Read, Update & Delete users in Identity Membership , Hi I'm following this article to delete a user in Identity 2.0 http://www.asp.net/mvc/​tutorials/mvc-5/introduction/examining-the-details-and-delete-methods However​  Using asp.net mvc5, my user management systems seems to work. I can login with google or with name/password.. but now I am working on a user management interface in which I need to be able to delete existing users. And this is starting to expose to me just how confusing the user management system is.

Update for ASP.NET Core 2.0 - hope this saves someone a bit of time

ApplicationDbContext context, 
UserManager<ApplicationUser> userManager, 
ApplicationUser user

var logins = await userManager.GetLoginsAsync(user);
var rolesForUser = await userManager.GetRolesAsync(user);

using (var transaction = context.Database.BeginTransaction())
{
    IdentityResult result = IdentityResult.Success;
    foreach (var login in logins)
    {
        result = await userManager.RemoveLoginAsync(user, login.LoginProvider, login.ProviderKey);
        if (result != IdentityResult.Success)
            break;
    }
    if (result == IdentityResult.Success)
    {
        foreach (var item in rolesForUser)
        {
            result = await userManager.RemoveFromRoleAsync(user, item);
            if (result != IdentityResult.Success)
                break;
        }
    }
    if (result == IdentityResult.Success)
    {
        result = await userManager.DeleteAsync(user);
        if (result == IdentityResult.Success)
            transaction.Commit(); //only commit if user and all his logins/roles have been deleted  
    }
}

ASP.NET MVC 5 how to delete a user and its related data - iOS, I'm not sure why you are not satisfied with default role provider from the ASP.NET engine (specially as you are a beginner), however if you want  Getting Started with ASP.NET MVC 5. Introduction to ASP.NET MVC 5. An updated version of this tutorial is available here using the latest version of Visual Studio. The new tutorial uses ASP.NET Core MVC, which provides many improvements over this tutorial. This tutorial teaches ASP.NET Core MVC with controllers and views.

I was looking also for the answer but finally this is what work well for me, even its old post but it may help for someone.

// GET: Users/Delete/5
    public ActionResult Delete(string id)
    {

        using (SqlConnection sqlCon = new SqlConnection(connectionString))
        {
            sqlCon.Open();

            string query = "DELETE FROM AspNetUsers WHERE Id = @Id";
            SqlCommand sqlCmd = new SqlCommand(query, sqlCon);
            sqlCmd.Parameters.AddWithValue("@Id", id);
            sqlCmd.ExecuteNonQuery();
        }

        return RedirectToAction("Index");
    }

    // POST: Users/Delete/5
    [HttpPost]
    public ActionResult Delete(string id, FormCollection collection)
    {
        try
        {
            // TODO: Add delete logic here

            return RedirectToAction("Index");
        }
        catch
        {
            return View();
        }
    }

Remove User from Roles in ASP.NET Identity 2.0.1, NET using Entity Framework to have full control over your user identity In the Models\IdentityModels.cs , we are going to delete the 1 2 3 4 5 6 7 8 9 10 11 12 public class AppUsersDbContext If you do not understand the terms related to SQL don't worry; the Microsoft.AspNet.Identity package we use  I want to using identity technology in MVC 5 with custom table , but i don't know how to do it . For example, my [user] table is id primary key identity(1,1), username nvarchar(50), password nvar

Configure ASP.NET Identity with a Code-First Approach, NET Identity 2.0: Customizing Users and Roles We will also add the basic ability to create, edit, and delete roles, and what all is involved with  Tutorial: Read related data - ASP.NET MVC with EF Core. 09/28/2019; 14 minutes to read +5; In this article. In the previous tutorial, you completed the School data model. In this tutorial, you'll read and display related data -- that is, data that the Entity Framework loads into navigation properties.

ASP.NET MVC 5 Identity: Extending and Modifying Roles, The Identity Samples project provides a solid platform to use as the basis for incorporating the Identity 2.0 framework into a new ASP.NET MVC  I have default project template of ASP.NET MVC 5 web site and I am trying to list all users with role names (not IDs). The query is: db.Users.Include(u => u.Roles).ToList() Then I want to pri

ASP.NET Identity 2.0: Customizing Users and Roles, Have an MVC C# app using identity but there are 2 database tables storing Deleting the user should delete all the related foreign keys unless BadRequest​); } //get User Data from Userid var user = await UserManager. Then I try to get the current user: ApplicationUser currentUser = db.Users.FirstOrDefault (x => x.Id == User.Identity.GetUserId ()); But I get the following exception: LINQ to Entities does not recognize the method 'System.String GetUserId (System.Security.Principal.IIdentity)' method, and this method cannot be translated into a store

Comments
  • Hi Horizon_Net, I have solved this problem by going the same way. Thank you for your explanation :) I actually don't know what is use of IdentityUser.
  • IdentityUser is the base class provided by Entity Framework (if you use it) to customize your user object to your needs. The base implementation gives you some basic properties, such as email address or user name, you can work with. With a child class you can extend it with your own properties, such as first name or last name. In most tutorials and examples you will see an implementation called ApplicationUser. If you want to know more you definitely should have a look at Scott Allen's blog
  • Thanks Horizon_Net :)
  • RemoveLoginAsync requires two parameters. Without the .ToList() on logins and rolesForUser I get an exception saying the Enumerable has been modified and cannot continue. I also needed to change _userManager to UserManager but that seemed to be specific to me. The difference was UserManager's get is return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>(); and for some reason without doing that .FindByIdAsync(id) would return null.
  • Also note that if you are going to use [ValidateAntiForgeryToken] then you need to include @Html.AntiForgeryToken() in your View
  • Please don't answer just with source code. Try to provide a nice description about how your solution works. See: stackoverflow.com/help/how-to-answer. Thanks!