播种管理员数据库角色未添加

时间:2017-12-08 10:06:34

标签: c# .net-core asp.net-identity asp.net-core-2.0

我在让管理员用户拥有管理员角色方面遇到了一些问题。创建用户并成功后,我尝试使用AddToRoleAsync添加admin角色。但我不确定为什么它没有被添加。然后我尝试检查,如果管理员没有管理员角色,它会添加它。它看起来像命令执行但我没有看到它添加到数据库中。

这是我的代码:

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="admin@admin.com",
               NormalizedEmail="ADMIN@ADMIN.COM",
               UserName="admin@admin.com",
               NormalizedUserName="ADMIN",
               EmailConfirmed = true,
           };
           var result = await _userManager.CreateAsync(user, "Password123");
       }

       var adminuser = await _userManager.FindByEmailAsync("admin@admin.com");
       bool flag = await _userManager.IsInRoleAsync(adminuser, "Administrator");
       if(!flag)
       {
           var role = await _roleManager.FindByNameAsync("Administrator");
           await _userManager.AddToRoleAsync(adminuser, "Administrator");
            }
   }

如果你想要完整的DbIntilizer或更多代码,请告诉我。

任何人都知道我做错了什么?

编辑 重写它以遵循这一点 http://www.locktar.nl/programming/net-core/seed-database-users-roles-dotnet-core-2-0-ef/ 现在它有效。

1 个答案:

答案 0 :(得分:2)

我就是这样做的。

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);
            }


        }

从我的GitHub项目中发现的代码here