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: Cannot create a DbSet for 'ApplicationUser' because this type is not included in the model for the context.
Startup:
services.AddIdentity<ApplicationUser, IdentityRole>(options =>
{
//password options
options.Password.RequireDigit = false;
// ...
})
I am using a standard ApplicationUser:
public class ApplicationUser : IdentityUser
{
}
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>
to AplicationContext
dotnet ef
I found the problem. My ApplicationContext
was inheriting from DbContext
. I changed it to IdentityDbContext<ApplicationUser>
and it works.
Create new context class which inherit IdentityDbContext.
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// Customize the ASP.NET Identity model and override the defaults if needed.
// For example, you can rename the ASP.NET Identity table names and more.
// Add your customizations after calling base.OnModelCreating(builder);
}
}
and in startup.cs file add below code
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(connection));
This will help you for database first approach.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With