InvalidOperationException: Can not create a DbSet for 'ApplicationUser' because this type is not included in the model for the context

0

I already have a database created in Sql Server, then I execute command:

PM> Scaffold-DbContext "Server=(localdb)\mssqllocaldb;Database=Teste;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Entities

After the command, created an "Entities" folder, after that it follows code in DbContext:

TestContext: DbContext

public partial class TesteContext : DbContext
{
    public virtual DbSet<AspNetRoles> AspNetRoles { get; set; }
    public virtual DbSet<AspNetUserClaims> AspNetUserClaims { get; set; }
    public virtual DbSet<AspNetUserLogins> AspNetUserLogins { get; set; }
    public virtual DbSet<AspNetUserRoles> AspNetUserRoles { get; set; }
    public virtual DbSet<AspNetUsers> AspNetUsers { get; set; }

    etc ...
}

ApplicationDbContext:

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);
    }
}

Startup.cs:

// Add framework services.
services.AddDbContext<TesteContext>(options =>
    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

services.AddIdentity<ApplicationUser, IdentityRole>()
    .AddEntityFrameworkStores<TesteContext>()
    .AddDefaultTokenProviders();

AccountController:

public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null)
{
    ViewData["ReturnUrl"] = returnUrl;
    if (ModelState.IsValid)
    {
        var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
        var result = await _userManager.CreateAsync(user, model.Password);
        if (result.Succeeded)
        {
            // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=532713
            // Send an email with this link
            //var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
            //var callbackUrl = Url.Action(nameof(ConfirmEmail), "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
            //await _emailSender.SendEmailAsync(model.Email, "Confirm your account",
            //    $"Please confirm your account by clicking this link: <a href='{callbackUrl}'>link</a>");
            await _signInManager.SignInAsync(user, isPersistent: false);
            _logger.LogInformation(3, "User created a new account with password.");
            return RedirectToLocal(returnUrl);
        }
        AddErrors(result);
    }

    // If we got this far, something failed, redisplay form
    return View(model);
}

The problem is on the line:

var result = await _userManager.CreateAsync(user, model.Password);

Error:

  

InvalidOperationException: Can not create a DbSet for 'ApplicationUser'   because this type is not included in the model for the context.

I try to create a new line in the database "Test".

Any solution?

    
asked by anonymous 05.08.2017 / 22:10

1 answer

0

You have defined two different contexts: TestContext and ApplicationDbContext . I'll focus on the Identity context.

Startup

Use the ApplicationDbContext for AddEntityFrameworkStores :

services.AddIdentity<ApplicationUser, IdentityRole>()
   .AddEntityFrameworkStores<ApplicationDbContext>()
   .AddDefaultTokenProviders();

In the Configure method, add (only confirming):

app.UseIdentity();
    
01.09.2017 / 09:49