Home > Software engineering >  Adding role to Identity programmatically
Adding role to Identity programmatically

Time:11-07

Before every thing I should say: "Why things that used to be easy have become so difficult now!!!!"

I create a Class Library project for my EF data context. I want to use Identity too. So I create context class like this:

public class Context : IdentityDbContext
{
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("Server=.;Database=MyDB1;Trusted_Connection=True;");
        base.OnConfiguring(optionsBuilder);
    }
}

and I add migration and update database. So I want to write some code to add a role to role table and use : RoleManager<IdentityRole> :

private readonly RoleManager<IdentityRole> _rolesManager;

public RoleRepository()
{
    _rolesManager = new RoleManager<IdentityRole>();
}

public async Task AddRole(string roleName)
{
    var role = new IdentityRole();
    role.Name = roleName;
    await _roleManager.CreateAsync(role);
}

the problem is I can't instantiate from RoleManager<IdentityRole> and I get this error:

There is no argument given that corresponds to the required formal parameter 'store' of 'RoleManager.RoleManager(IRoleStore, IEnumerable<IRoleValidator>, ILookupNormalizer, IdentityErrorDescriber, ILogger<RoleManager>)'

How can I add this parmaters when instantiate from RoleManager<IdentityRole>?

How can I add role To Role table in a class library project?

Thanks

CodePudding user response:

Hope below code might help you.

using (var context = new ApplicationDbContext())
          {
            var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context), null, null, null, null);

            var role = new IdentityRole(RoleName);

            var result = await roleManager.RoleExistsAsync(RoleName);
            if (!result)
            {
              await roleManager.CreateAsync(role);
            }
          }
  • Related