Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 380
FSMaxB Avatar asked Sep 01 '16 03:09

FSMaxB


2 Answers

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

like image 142
FSMaxB Avatar answered Oct 26 '22 23:10

FSMaxB


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.

like image 40
aditya mukkawar Avatar answered Oct 26 '22 22:10

aditya mukkawar