asp.net-core – 如何在EF Core 2.1.0中为Admin用户播种?

我有一个使用EF Core 2.1.0的ASP.NET Core 2.1.0应用程序.

如何使用Admin用户数据库播种并为其授予管理员角色?我找不到任何关于此的文件.

解决方法

因为用户不能以正常方式在Identity中播种,就像其他表使用.NET Core 2.1的.HasData()播种一样.

.NET Core 2.1中的种子角色使用ApplicationDbContext类中给出的代码

protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        // Customize the ASP.NET Identity model and override the defaults if needed.
        // For example,you can rename the ASP.NET Identity table names and more.
        // Add your customizations after calling base.OnModelCreating(builder);

        modelBuilder.Entity<IdentityRole>().HasData(new IdentityRole { Name = "Admin",normalizedname = "Admin".toupper() });
    }

具有角色的种子用户按照以下步骤操作.

第1步:创建新类

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

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

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

步骤2:现在修改Startup.cs类中的ConfigureServices方法.

修改前:

services.AddDefaultIdentity<IdentityUser>()
            .AddEntityFrameworkStores<ApplicationDbContext>();

修改后:

services.AddDefaultIdentity<IdentityUser>().AddRoles<IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>();

步骤3:修改Startup.cs类中Configure Method的参数.

修改前:

public void Configure(IApplicationBuilder app,IHostingEnvironment env)
    {
        //..........
    }

修改后:

public void Configure(IApplicationBuilder app,IHostingEnvironment env,UserManager<IdentityUser> userManager)
    {
        //..........
    }

第4步:调用Seed(ApplicationDbInitializer)类的方法

ApplicationDbInitializer.SeedUsers(userManager);

相关文章

这篇文章主要讲解了“WPF如何实现带筛选功能的DataGrid”,文...
本篇内容介绍了“基于WPF如何实现3D画廊动画效果”的有关知识...
Some samples are below for ASP.Net web form controls:(fr...
问题描述: 对于未定义为 System.String 的列,唯一有效的值...
最近用到了CalendarExtender,结果不知道为什么发生了错位,...
ASP.NET 2.0 page lifecyle ASP.NET 2.0 event sequence cha...