lee-r
9/18/2019 - 10:34 AM

Startup.cs To Create Admin and Roles

      private void CreateRolesAndAdminAccount()
        {
            var context = new ApplicationDbContext();

            // Create a RoleStore object by using the ApplicationDbContext object. 
            // The RoleStore is only allowed to contain IdentityRole objects.
            var roleStore = new RoleStore<IdentityRole>(context);

            // Create a RoleManager object that is only allowed to contain IdentityRole objects.
            // When creating the RoleManager object, you pass in (as a parameter) a new RoleStore object. 
            var roleMgr = new RoleManager<IdentityRole>(roleStore);

            // Then, you create the "canEdit" role if it doesn't already exist.
            if (!roleMgr.RoleExists("Admin"))
            {
                 roleMgr.Create(new IdentityRole { Name = "Admin" });
            }
            if (!roleMgr.RoleExists("User"))
            {
                 roleMgr.Create(new IdentityRole { Name = "User" });
            }

            var userStore = new UserStore<ApplicationUser>(context);
            var um = new UserManager<ApplicationUser>(userStore);

            if (um.FindByName("admin") == null)
            {
                um.Create(new ApplicationUser { UserName= "admin", Email = "admin" }, "devdev");
                var id = um.FindByName("admin").Id;
                if (!um.IsInRole(id, "Admin")) {
                    um.AddToRole(id, "Admin");
                }
            }

        }