我在Configuration.cs文件的Seed方法中有以下代码:
var userStore = new UserStore<ApplicationUser>();
var manager = new UserManager<ApplicationUser>(userStore);
IdentityResult result = manager.Create(new ApplicationUser() { UserName = "test@mail.com", Email = "test@mail.com", Name = "Martin Tracey" }, "password");
if (result.Succeeded) { Console.WriteLine("User created successfully"); }
else {
Console.WriteLine("Something went wrong. result is "+result.ToString());
foreach (var error in result.Errors) Console.WriteLine(error);
}
无论出于何种原因,manager.Create
来电都会返回null
。
知道为什么这个方法会返回null吗?
答案 0 :(得分:0)
我明白了!这是一个非常简单的解决方案。
我的userStore
变量没有允许它访问和写入数据库的DbContext。简单的解决方案是使用传递给Seed方法的上下文。现在就像魅力一样!见下文:
protected override void Seed(MyFirstWebApplication.Models.ApplicationDbContext context)
{
if( !context.Users.Any( u => u.Email == "test@mail.com" ) )
{
var userStore = new UserStore<ApplicationUser>(context);
var manager = new UserManager<ApplicationUser>(userStore);
var user = new ApplicationUser() { UserName = "test@mail.com", Email = "test@mail.com", Name = "Martin Tracey" };
IdentityResult result = manager.Create(user, "password");}
}
}