我正在使用Code First迁移构建MVC 5应用程序,并尝试使用默认管理员用户为我的数据库设定种子。我可能在这里做出错误的假设,但我认为我需要使用异步方法来添加用户和角色,因为我收到的错误是关于之前不存在的用户。现在,当我在软件包管理器控制台中运行update-database
命令时,它会崩溃Visual Studio 2013。我不知所措。
我在崩溃之前没有收到错误,而且我还没弄清楚如何在PMC中调试代码运行。这是我的种子方法中的代码:
//Add default users here:
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
var silkster = new NewUser() { UserName = "silkster", Password = "Passw0rd!", Email = "dan@silkster.com", Roles = new List<string>() { "Admin" } };
var defaultUser = await UserManager.FindByNameAsync(silkster.UserName);
var newUserResult = IdentityResult.Success;
if (defaultUser == null)
{
var user = new ApplicationUser() { UserName = silkster.UserName, Email = silkster.Email };
newUserResult = await UserManager.CreateAsync(user, silkster.Password);
}
if (newUserResult == IdentityResult.Success)
{
var results = new List<IdentityResult>();
IdentityResult result;
foreach (string role in silkster.Roles)
{
if (!RoleManager.RoleExists(role))
{
result = await RoleManager.CreateAsync(new IdentityRole(role));
results.Add(result);
}
result = await UserManager.AddToRoleAsync(silkster.UserName, role);
results.Add(result);
}
}
答案 0 :(得分:2)
我找到了一些帮助我解决Visual Studio崩溃问题的信息here。
将此方法添加到Configuration.cs:
protected async Task<bool> AddRoleAndUser(ZTTDD.Models.ApplicationDbContext context, NewUser newUser)
{
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
IdentityResult result = IdentityResult.Success;
var user = UserManager.FindByName(newUser.UserName);
if (user != null)
{
user = new ApplicationUser() { UserName = newUser.UserName, Email = newUser.Email };
result = await UserManager.CreateAsync(user, newUser.Password);
if (!result.Succeeded)
Console.Write("Unable to create user: " + newUser.UserName);
return false;
}
foreach (string r in newUser.Roles)
{
if (!RoleManager.RoleExists(r))
{
var role = new IdentityRole(r);
result = await RoleManager.CreateAsync(role);
if (!result.Succeeded)
Console.Write("Unable to create role: " + r);
return false;
}
result = await UserManager.AddToRoleAsync(user.Id, r);
if (!result.Succeeded)
{
Console.Write("Unable to add user '" + newUser.UserName + "' to role '" + r + "'.");
}
}
return result.Succeeded;
}
然后我在Seed方法中重构了我的代码,如下所示:
var silkster = new NewUser() { UserName = "silkster", Password = "Passw0rd!", Email = "dan@silkster.com", Roles = new List<string>() { "Admin" } };
var seedUserSuccess = await AddRoleAndUser(context, silkster);
if (!seedUserSuccess)
{
Console.Write("Seeding failed for user: " + silkster.UserName);
}