EF核心种子用户角色问题

时间:2019-10-30 14:48:37

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

我设法播种了管理员的详细信息,例如用户名和密码,因此它们出现在表格中。但是,我遇到的问题是角色“ admin”没有保存在表中的任何位置。我在这里想念什么吗?我是asp.net核心的新手,所以我只是想把它包裹住。

下面是我的播种课程:

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

下面是我的configure方法签名:

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

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

ApplicationDbInitializer.SeedUsers(userManager);

以下是我的添加身份:

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

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

2 个答案:

答案 0 :(得分:1)

您还需要植入Roles,然后将用户链接到所需的角色。

检查this answer,以获取有关如何播种数据的更多信息。

答案 1 :(得分:0)

您可以查看我的完整代码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();
}