InvalidOperationException when registering a new user with ASP .NET Core Identity and EntityFrameworkCore

社会主义新天地 提交于 2019-12-01 17:41:13

问题


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:

  • Adding DbSet<ApplicationUser> to AplicationContext
  • I did create and apply a new migration via dotnet ef

回答1:


I found the problem. My ApplicationContext was inheriting from DbContext. I changed it to IdentityDbContext<ApplicationUser> and it works.




回答2:


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.



来源:https://stackoverflow.com/questions/39262222/invalidoperationexception-when-registering-a-new-user-with-asp-net-core-identit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!