Invalidoperationexception: Cannot create a Dbset for 'Applicationuser' because this type is not included in the model for the context

Asked

Viewed 1,295 times

0

I already have a database created in Sql Server, so I executed command:

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

After the command, you created a "Entities" folder, after which you follow code in Dbcontext:

Testecontext : 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: Cannot 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 data set "Test".

Some solution ?

1 answer

0

You defined two different contexts: Testecontext and Applicationdbcontext. Let me focus on the context of Identity.

Startup

Use the Applicationdbcontext for Addentityframeworkstores:

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

In the method Configure add ( just confirming ):

app.UseIdentity();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.