我遇到了使用Identity v2種子數據庫的問題。我將MVC5項目中的IdentityModel分離到我的數據訪問層,並在其中設置EF Migrations。所以我註釋掉這裏面使用「IdentityConfig.cs」創建初始用戶,並把代碼看起來像這樣Identity 2的種子數據庫
protected override void Seed(Repository.DataContext.IdentityDb context)
{
// var userManager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
// var roleManager = HttpContext.Current.GetOwinContext().Get<ApplicationRoleManager>();
var owinContext = new OwinContext();
var userManager = owinContext.GetUserManager<ApplicationUserManager>();
var roleManager = owinContext.Get<ApplicationRoleManager>();
const string name = "[email protected]";
const string password = "[email protected]";
const string roleName = "Admin";
// //Create Role Admin if it does not exist
var role = roleManager.FindByName(roleName);
if (role == null)
{
role = new IdentityRole(roleName);
var roleresult = roleManager.Create(role);
}
var user = userManager.FindByName(name);
if (user == null)
{
user = new ApplicationUser { UserName = name, Email = name };
var result = userManager.Create(user, password);
result = userManager.SetLockoutEnabled(user.Id, false);
}
// // Add user admin to Role Admin if not already added
var rolesForUser = userManager.GetRoles(user.Id);
if (!rolesForUser.Contains(role.Name))
{
var result = userManager.AddToRole(user.Id, role.Name);
}
}
現在,當我運行命令更新數據庫我的種子庫中的代碼,我得到了一個錯誤
Value cannot be null.
Parameter name: manager
那樣子,我的代碼
var userManager = owinContext.GetUserManager<ApplicationUserManager>();
var roleManager = owinContext.Get<ApplicationRoleManager>();
任何建議,請這兩行越來越空?
看線51位置:https://raw.githubusercontent.com/OdeToCode/MVC5_Samples/master/identity/BasicIdentityWithDiagrams /Migrations/Configuration.cs我不認爲你會在Seed方法中使用Owin成功,除非你在應用程序內運行Seed。如果您從包管理器控制檯運行Seed,Owin將不在或未配置。 – OdeToCode