Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting roles with Asp.net Identity

Tags:

c#

asp.net-mvc

Can someone describe to me just how you delete roles with asp.net identity. I tried the following, but it did not work and I received a Specified Method is not supported error:

public async Task DeleteRole(string role)
    {
        // delete role
        var roleStore = new RoleStore<IdentityRole>(new Context());
        await roleStore.DeleteAsync(new IdentityRole(role));


    }

Not sure if this is referring to something with my async logic, or specifically with asp.net identity itself. Nevertheless can someone demonstrate to me how to make this work correctly. There is virtually no documentation available on the new identity system for asp.net at this time.

like image 952
user1206480 Avatar asked Nov 19 '13 18:11

user1206480


2 Answers

The Identity context (IdentityDbContext) contains the role store. So you would (assuming AppDb is your context):

var role = AppDb.Roles.Where(d => d.Name == "my role name").FirstOrDefault();
AppDb.Roles.Remove(role);
AppDb.SaveChanges();

You basically treat it as a normal EntityFramework DbSet, it's inherited from the IdentityDbContext.

like image 151
Tony Basallo Avatar answered Nov 16 '22 23:11

Tony Basallo


I know that is an old question, but I've tried a way that doesn't touch store (or DbContext) directly.

I've used it in ASP.NET Core 2.1

var role = await _roleManager.FindByNameAsync(roleName);
var result = await _roleManager.DeleteAsync(role);

needless to say that it:

  • delete role that assigned to user -> AspNetUserRoles
  • delete role's claims -> AspNetRoleClaims
  • delete role itself -> AspNetRoles
like image 31
Soren Avatar answered Nov 16 '22 22:11

Soren