Search code examples
ef-code-firstasp.net-identity-2

Code First Seed Asp.net Identity


I am working on a new requirement for a project which has been lived for couple of months.I am using Code First (EF6) with Asp.net Identity. I need to add a new user role in the seed method and attach this role to the admin. How can I add a new role to the admin within the seed? Below is the code snippet of my seed method.

 protected override void Seed(myDbContext context)
    {
if (!context.Roles.Any())
        {
            var userManager =
                new UserManager<AppUser, Guid>(
                    new UserStore<AppUser, AppRole, Guid, AppUserLogin, AppUserRole, AppUserClaim>(context));
            var roleManager = new RoleManager<AppRole, Guid>(new RoleStore<AppRole, Guid, AppUserRole>(context));

            var adminRole = new AppRole() {Name = "admin"};
            roleManager.Create(adminRole);


            var admin = new Admin()
            {
                UserName = "test@test.com",
                EmailConfirmed = true,
                SecurityStamp = Guid.NewGuid().ToString()
            };
            admin.Roles.Add(new AppUserRole()
            {
                RoleId = adminRole.Id
            });


            userManager.Create(admin, "pwd");

            // user.Roles.Add(new IdentityUserRole { RoleId = userRole.Id, UserId = user.Id });

            base.Seed(context);
        }

    }

Solution

  • If you have a live application and have run a migration, then your code won't work since !context.Roles.Any() is going to be false since you now have roles. To make your script idempotent, do something like this:

    protected override void Seed(myDbContext context)
    {
    
        var userManager = new UserManager<AppUser, Guid>(new UserStore<AppUser, AppRole, Guid, AppUserLogin, AppUserRole, AppUserClaim>(context));
        var roleManager = new RoleManager<AppRole, Guid>(new RoleStore<AppRole, Guid, AppUserRole>(context));
    
        // see if this role exists -- repeat for all roles
        if (!context.Roles.Any(r => r.Name == "admin"))
        {
            var adminRole = new AppRole() {Name = "admin"};
            roleManager.Create(adminRole);
        }
    
        // see if the user exists -- repeat for all users
        if (!context.Users.Any(u => u.UserName == "test@test.com")
        {
            var admin = new Admin()
            {
                UserName = "test@test.com",
                EmailConfirmed = true,
                SecurityStamp = Guid.NewGuid().ToString()
            };
            userManager.Create(admin, "pwd");
        }
    
        // see if the user has the role -- repeat for all roles for user, all users
        if (!userManager.IsInRole(admin.Id, "admin")
        {
             userManager.AddToRole(admin.Id, "admin")
        }
    
        ...
    
        base.Seed(context);
    
    }