I am following a tutorial about roles but the default admin user is not created. The roles are created.
File Name: DbInitializerRepo
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using ShoppingCart2023.Data;
using ShoppingCart2023.Models;
namespace ShoppingCart2023.DbInitializer
{
public class DbInitializerRepo : IDbInitializer
{
private readonly UserManager<IdentityUser> _userManager;
private readonly RoleManager<IdentityRole> _roleManager;
private readonly ApplicationDbContext _context;
public DbInitializerRepo(UserManager<IdentityUser> userManager, RoleManager<IdentityRole> roleManager, ApplicationDbContext context)
{
_userManager = userManager;
_roleManager = roleManager;
_context = context;
}
public void Initializer()
{
try
{
if (_context.Database.GetPendingMigrations().Count() > 0)
{
_context.Database.Migrate();
}
}
catch (Exception)
{
throw;
}
if (!_roleManager.RoleExistsAsync(WebSiteRole.Role_Admin).GetAwaiter().GetResult())
{
_roleManager.CreateAsync(new IdentityRole(WebSiteRole.Role_Admin)).GetAwaiter().GetResult();
_roleManager.CreateAsync(new IdentityRole(WebSiteRole.Role_User)).GetAwaiter().GetResult();
_roleManager.CreateAsync(new IdentityRole(WebSiteRole.Role_Employee)).GetAwaiter().GetResult();
_userManager.CreateAsync(new ApplicationUser
{
UserName = "ramitaherwahdan1978@gmail.com",
Email = "ramitaherwahdan1978@gmail.com",
Name = "Admin",
Address = "Al Manaseer Area",
City = "Abu-Dhabi",
PinCode = "123456"
}, "Admin@123").GetAwaiter().GetResult();
ApplicationUser user = _context.ApplicationUsers.FirstOrDefault(x => x.Email == "ramitaherwahdan1978@gmail.com");
_userManager.AddToRoleAsync(user, WebSiteRole.Role_Admin).GetAwaiter().GetResult();
}
return;
}
}
}
the WebSiteRole:
namespace ShoppingCart2023
{
public static class WebSiteRole
{
public const string Role_User = "Customer";
public const string Role_Admin = "Admin";
public const string Role_Employee = "Employee";
}
}
File Name: ApplicationDbContext
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using ShoppingCart2023.Models;
namespace ShoppingCart2023.Data
{
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<Category> categories { get; set; }
public DbSet<Product> products { get; set; }
public DbSet<ApplicationUser> ApplicationUsers { get; set; }
}
}