如果您有一个实时应用程序并运行了迁移,那么您的代码将无法运行!上下文。角色。Any()将为false,因为您现在有了角色。要使脚本幂等,请执行以下操作:
protected override void Seed(myDbContext context)
{
var userManager = new UserManager<AppUser, Guid>(new UserStore<AppUser, AppRole, Guid, AppUserLogin, AppUserRole, AppUserClaim>(context));
var roleManager = new RoleManager<AppRole, Guid>(new RoleStore<AppRole, Guid, AppUserRole>(context));
// see if this role exists -- repeat for all roles
if (!context.Roles.Any(r => r.Name == "admin"))
{
var adminRole = new AppRole() {Name = "admin"};
roleManager.Create(adminRole);
}
// see if the user exists -- repeat for all users
if (!context.Users.Any(u => u.UserName == "test@test.com")
{
var admin = new Admin()
{
UserName = "test@test.com",
EmailConfirmed = true,
SecurityStamp = Guid.NewGuid().ToString()
};
userManager.Create(admin, "pwd");
}
// see if the user has the role -- repeat for all roles for user, all users
if (!userManager.IsInRole(admin.Id, "admin")
{
userManager.AddToRole(admin.Id, "admin")
}
...
base.Seed(context);
}