I am having some issues with getting my admin user have an admin role. Once I create a user and it succeeds I tried adding the admin role with AddToRoleAsync. But I am not sure why it's not being added. I then tried to have a check so that if the admin has no admin role it would add it. It looks like the command executes but I don't see it added to the database.
This is my code:
public async Task CreateAdmin()
{
// Add roles
string[] roles = new string[] {"Administrator", "User"};
foreach(string role in roles)
{
bool result = await _roleManager.RoleExistsAsync(role);
if(!result)
{
await _roleManager.CreateAsync(new IdentityRole(role));
}
}
// Add admin user
if (!_context.Users.Any(u => u.UserName == "Admin"))
{
var user = new Users
{
Email="[email protected]",
NormalizedEmail="[email protected]",
UserName="[email protected]",
NormalizedUserName="ADMIN",
EmailConfirmed = true,
};
var result = await _userManager.CreateAsync(user, "Password123");
}
var adminuser = await _userManager.FindByEmailAsync("[email protected]");
bool flag = await _userManager.IsInRoleAsync(adminuser, "Administrator");
if(!flag)
{
var role = await _roleManager.FindByNameAsync("Administrator");
await _userManager.AddToRoleAsync(adminuser, "Administrator");
}
}
If you want the full DbIntilizer or more code let me know.
Anyone know what I am doing wrong?
Edit Reworked it to follow this http://www.locktar.nl/programming/net-core/seed-database-users-roles-dotnet-core-2-0-ef/ and now it works.
This is how i do it.
public async Task InitializeDatabase(IApplicationBuilder app)
{
using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
{
// Create DB
serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>().Database.Migrate();
// Add roles
var roleManager = serviceScope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole<long>>>();
if (!roleManager.Roles.Any())
{
foreach (var role in Config.GetTestRolls())
{
await roleManager.CreateAsync(role);
}
}
// Add users
var userManager = serviceScope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
if (userManager.Users.Any()) return;
foreach (var user in Config.GetTestUsers())
{
await userManager.CreateAsync(user, "Password123!");
}
// find first user add to first role (hack)
var adminUser = await userManager.FindByEmailAsync(Config.GetTestUsers().FirstOrDefault()?.Email);
if (adminUser != null)
{
await userManager.AddToRoleAsync(adminUser, Config.GetTestRolls().FirstOrDefault()?.Name);
}
}
Code ripped from my GitHub Project found here