使用ASP .NET Core身份和EntityFrameworkCore注册新用户时出现InvalidOperationException [英] InvalidOperationException when registering a new user with ASP .NET Core Identity and EntityFrameworkCore
问题描述
我正在遵循有关使用身份的文档并且正在尝试注册新用户(执行register操作),但是失败并出现以下错误:
I'm following the documentation for using Identity and am trying register a new user (executing the register action), but it fails with the following error:
InvalidOperationException:无法创建DbSet for'ApplicationUser'
,因为此类型未包含在上下文模型中。
InvalidOperationException: Cannot create a DbSet for 'ApplicationUser' because this type is not included in the model for the context.
启动:
services.AddIdentity<ApplicationUser, IdentityRole>(options =>
{
//password options
options.Password.RequireDigit = false;
// ...
})
我正在使用标准的ApplicationUser:
I am using a standard ApplicationUser:
public class ApplicationUser : IdentityUser
{
}
在AccountController中注册操作:
Register action in 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);
}
我已经尝试过以下操作:
I already tried the following:
- 将
DbSet< ApplicationUser>
添加到AplicationContext
- 我确实通过
dotnet ef
- Adding
DbSet<ApplicationUser>
toAplicationContext
- I did create and apply a new migration via
dotnet ef
推荐答案
我发现了问题。我的 ApplicationContext
是从 DbContext
继承的。我将其更改为 IdentityDbContext< ApplicationUser>
,它可以正常工作。
I found the problem. My ApplicationContext
was inheriting from DbContext
. I changed it to IdentityDbContext<ApplicationUser>
and it works.
这篇关于使用ASP .NET Core身份和EntityFrameworkCore注册新用户时出现InvalidOperationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!