skip to Main Content

I have a default identity in ASP.NET MVC 5, I can do CRUD on User and Role . But I don’t have idea to do CRUD in table AspNetUserRoles. Because I want to make a user management with that table by matching UserId and RoleId .
Here’s my AplicationDbContext

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("DefaultConnection", false)
    {
    }

    public DbSet<ArrayDataVM> ArrayDatas { get; set; }
    public DbSet<Sender> Senders { get; set; }
    public DbSet<SMSDetail> SMSDetails { get; set; }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }
}

And the AccountViewModel is still default that’s too long too type here.

Can you give me the answer? thanks

2

Answers


  1. as suggested by @Georgy Tarasov in comments section, you can use UserManager and RoleManager for CRUD operations of users and roles and user roles.
    I have got an article which will help you.

    Here is a quick code.

    ApplicationDbContext context = new ApplicationDbContext();    
      
    var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));    
    var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); 
    
    if (!roleManager.RoleExists("Admin"))    
    {    
      var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();    
      role.Name = "Admin";    
      roleManager.Create(role); 
    }
    
    

    If you want to add user to this role, you can do by just adding userManager.AddToRole(userId, "Admin")

    For full article, click here

    Login or Signup to reply.
  2. Simple example of getting roles, finding user, and assigning him to role Admin.

    var context = new ApplicationDbContext();
    var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
    var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
    var roles = roleManager.Roles.ToList();
    
    var user = await userManager.FindByEmailAsync("[email protected]");
    userManager.AddToRoleAsync(user.Id, "Admin");
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search