【问题标题】:EF Core Seeding User Role Issue [duplicate]EF Core 播种用户角色问题 [重复]
【发布时间】:2020-02-25 21:47:39
【问题描述】:

我已设法为管理员的详细信息(例如用户名和密码)播种,因此它们出现在表格中。但是,我遇到的问题是角色“管理员”没有保存在表中的任何位置。我在这里错过了什么吗?我是 asp.net core 的新手,所以我只是想绕开它。

下面是我的播种课:

public class ApplicationDbInitializer
{
    public static void SeedUsers(UserManager<IdentityUser> userManager)
    {
        if (userManager.FindByEmailAsync("abc@outlook.com").Result == null)
        {
            IdentityUser user = new IdentityUser
            {
                UserName = "abc@outlook.com",
                Email = "abc@outlook.com"
            };

            IdentityResult result = userManager.CreateAsync(user, "Passwordtest123!").Result;

            if (result.Succeeded)
            {
                userManager.AddToRoleAsync(user, "Admin").Wait();
            }
        }
    }
}

下面是我的配置方法签名:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, UserManager<IdentityUser> userManager)

下面是我调用我的种子方法:

ApplicationDbInitializer.SeedUsers(userManager);

下面是我添加的身份:

    services.AddIdentity<IdentityUser, IdentityRole>()
         .AddEntityFrameworkStores<RestaurantWebContext>();

代码中是否缺少某些内容,我在角色表或用户表中看不到管理员。

【问题讨论】:

    标签: c# entity-framework asp.net-core


    【解决方案1】:

    您还需要播种Roles,然后将用户链接到您想要的角色。

    查看this answer,了解有关如何播种数据的更多信息。

    【讨论】:

      【解决方案2】:

      你可以查看我的完整代码here

      下面是一个例子

      var user = new User
      {
          Id = new Guid("a1add451-7dd2-46fd-9877-1996e3f1fb4c").ToString(),
          Email = "",
          NormalizedEmail = "".ToUpper(),
          UserName = "",
          NormalizedUserName = "tony5".ToUpper(),
          EmailConfirmed = true,
          PhoneNumberConfirmed = true,
          LockoutEnabled = false,
          SecurityStamp = Guid.NewGuid().ToString()
      };
      
      using (var context = new ApplicationDbContext(
          serviceProvider.GetRequiredService<DbContextOptions<ApplicationDbContext>>()))
      {
          var roles = new[]
              {"Owner", "Administrator", "Editor", "ContentWriter"};
      
          var roles1 = new[]
              {"Administrator"};
      
          var roles2 = new[]
              {"Editor"};
      
          var roles4 = new[]
              {"Owner", "Administrator"};
      
          if (!context.Roles.Any())
          {
              foreach (var role in roles)
              {
                  var roleStore = new RoleStore<ApplicationRole>(context);
      
                  await roleStore.CreateAsync(new ApplicationRole
                  {
                      Name = role,
                      NormalizedName = role.ToUpper()
                  });
              }
          }
      
          if (!context.Users.Any())
          {
              await SeedUser(user, context, serviceProvider, roles4);
          }
      }
      
      
      private static async Task SeedUser(
          User user, 
          ApplicationDbContext context, 
          IServiceProvider serviceProvider,
          string[] roles)
      {
          var password = new PasswordHasher<User>();
          var hashed = password.HashPassword(user, "123456");
          user.PasswordHash = hashed;
          var userStore = new UserStore<User>(context);
      
          await userStore.CreateAsync(user);
          await EnsureRole(serviceProvider, user.Email, roles);
          await context.SaveChangesAsync();
      }
      

      【讨论】:

        猜你喜欢
        • 2018-09-03
        • 2020-09-13
        • 1970-01-01
        • 2016-10-03
        • 2021-07-10
        • 2012-11-13
        • 1970-01-01
        • 2018-08-10
        • 2018-02-28
        相关资源
        最近更新 更多