使用ASP .NET Core Identity和EntityFrameworkCore注册新用户时出现InvalidOperationException

FSM*_*axB 5 c# entity-framework asp.net-core-1.0 asp.net-core-identity

我正在关注使用Identity文档并尝试注册一个新用户(执行注册操作),但它失败并出现以下错误:

InvalidOperationException:无法为"ApplicationUser"创建DbSet,因为此类型未包含在上下文的模型中.

启动:

services.AddIdentity<ApplicationUser, IdentityRole>(options =>
{
    //password options
    options.Password.RequireDigit = false;
    // ...
})
Run Code Online (Sandbox Code Playgroud)

我使用的是标准的ApplicationUser:

public class ApplicationUser : IdentityUser
{
}
Run Code Online (Sandbox Code Playgroud)

在AccountController中注册操作:

public async Task<IActionResult> Register(RegisterViewModel viewModel)
{
    if (ModelState.IsValid)
    {
        var user = new ApplicationUser { UserName = viewModel.UserName, Email = viewModel.Email };
        var result = await _userManager.CreateAsync(user, viewModel.Password); //<-- Exception happens here
        if (result.Succeeded)
        {
            await _signInManager.SignInAsync(user, isPersistent: false);
            _logger.LogInformation(3, "User created a new account with password.");
            return RedirectToAction(nameof(HomeController.Index), "Home");
        }

        string errorData = "";
        foreach (var error in result.Errors)
        {
            errorData += error.Description + '\n';
        }
        StoreErrorMessage("Failed to create the user!", errorData);
    }

    return View(viewModel);
}
Run Code Online (Sandbox Code Playgroud)

我已经尝试过以下方法:

  • 添加DbSet<ApplicationUser>AplicationContext
  • 我确实通过创建和应用新的迁移 dotnet ef

FSM*_*axB 12

我发现了这个问题.我ApplicationContext是继承自己的DbContext.我改变了它IdentityDbContext<ApplicationUser>,它的工作原理.