UserManager<ApplicationUser>.Create() is returning nul

本文关键字:is returning nul gt lt ApplicationUser UserManager Create | 更新日期: 2023-09-27 18:04:42

我在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吗?

UserManager<ApplicationUser>.Create() is returning nul

我明白了!这是一个非常简单的解决方案。

我的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");}
    }
}