解决方法
因为用户不能以正常方式在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);