【发布时间】:2020-03-31 15:47:53
【问题描述】:
我有以下迁移配置类:
namespace MVC_Authentication.Migrations
{
using Microsoft.AspNet.Identity.EntityFramework;
using MVC_Authentication.Models;
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
using System.Threading.Tasks;
internal sealed class MigrationConfiguration : DbMigrationsConfiguration<ApplicationDbContext>
{
public MigrationConfiguration()
{
AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = true;
ContextKey = "MVC_Authentication.Models.ApplicationDbContext";
}
protected override void Seed(ApplicationDbContext context)
{
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data.
SeedDatabase(context).GetAwaiter().GetResult();
}
protected async Task SeedDatabase(ApplicationDbContext ctx)
{
var roleManager = new ApplicationRoleManager(new RoleStore<IdentityRole>(ctx));
if (await roleManager.FindByNameAsync("Administrator") == null)
await roleManager.CreateAsync(new IdentityRole("Administrator"));
if (await roleManager.FindByNameAsync("User") == null)
await roleManager.CreateAsync(new IdentityRole("User"));
ApplicationUserManager userManager = new ApplicationUserManager(new UserStore<ApplicationUser>(ctx));
var user_Admin = new ApplicationUser()
{
SecurityStamp = Guid.NewGuid().ToString(),
UserName = "Admin",
Email = "myEmail",
EmailConfirmed = true
};
if (await userManager.FindByNameAsync(user_Admin.UserName) == null)
{
await userManager.CreateAsync(user_Admin, "MyPassword");
await userManager.AddToRoleAsync(user_Admin.Id, "User");
await userManager.AddToRoleAsync(user_Admin.Id, "Administrator");
}
}
}
}
但是当执行到达时:
if (await roleManager.FindByNameAsync("Administrator") == null)
应用程序锁定,我可以等待和等待。 也许我不应该在这里使用 RoleManager 和 UserManager ?这是播种角色和用户的唯一方法。 感谢您提供任何可能出错的提示。
【问题讨论】:
-
如果它的行为方式相同,您会尝试同步版本吗?
roleManager.FindByName() -
智能感知没有给我同步版本 FindByName()
-
尝试使用 RoleManager 而不是 ApplicationRoleManager;
var roleStore = new RoleStore<IdentityRole>(db); var roleManager = new RoleManager<IdentityRole>(roleStore); -
那行得通。谢谢。
-
哦,我不知道这会解决问题,哈哈。我添加了答案,请标记为正确的,也谢谢你!
标签: asp.net-mvc seeding