1
votes

When trying to add a new user using entity framework core I get the above error code. I know this has been asked on here before but I can't fix my issue with the solutions I have found so far.

Im trying to create a user with a username (email) and password using asp.net identity but I keep getting the following error message:

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

I have tried messing with the startup.cs file and the Model.BlogContext file as recommended on multiple threads here but can't seem to get around this message.

I'm pretty new to this, sorry if my question isn't clear.

Here's my code -

ApplicationContext:

namespace Blog3Prog.Models { class Message { [Key] public int MessageId { get; set; } public string UserName { get; set; } public string FullMessage { get; set; }

}
class Timeline
{
    [Key]
    public int UserId { get; set; }
    public int Posts { get; set; }
    public string Username { get; set; }
}
public class BlogContext : IdentityDbContext<ApplicationUser>
{
    public BlogContext(DbContextOptions<DbContext> options) : base()
    {

    }
        protected override void OnConfiguring(DbContextOptionsBuilder 
optionsBuilder)
        {

            optionsBuilder.UseSqlServer(@"Data Source= 
(localdb)\MSSQLLocalDB;Initial Catalog=master;Integrated 
Security=True;Connect 
Timeout=30;Encrypt=False;TrustServerCertificate=False; 
ApplicationIntent=ReadWrite;MultiSubnetFailover=False; Database=BlogProject 
;Trusted_Connection=True");
        }
        private DbSet<Message> Messages { get; set; }
        private DbSet<Timeline> Timelines { get; set; }
        private DbSet<ApplicationUser> applicationUsers { get; set; }
        public DbSet<Microsoft.AspNetCore.Identity.IdentityUserClaim<Guid>> 
IdentityUserClaims { get; set; }
        public DbSet<IdentityUserClaim<string>> IdentityUserClaim { get; 
set; }
        public new DbSet<ApplicationUser> Users { get; set; }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {

        }
    }
}

Startup.cs:

namespace Blog3Prog
{

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add 
services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<BlogContext>(options =>
 options.UseSqlServer(@"Data Source=(localdb)\MSSQLLocalDB;Initial 
Catalog=master;Integrated Security=True;Connect 

Timeout=30;Encrypt=False;TrustServerCertificate=False; 
ApplicationIntent=ReadWrit 
e;MultiSubnetFailover=False; Database=BlogProject 
;Trusted_Connection=True"));

        services.Configure<CookiePolicyOptions>(options =>
        {

            // This lambda determines whether user consent for non-essential 
cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;

        });

        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

        services.AddIdentity<Blog3Prog.Models.ApplicationUser, 
IdentityRole> ()
            .AddEntityFrameworkStores<DbContext>()
            .AddDefaultTokenProviders();

        services.AddMvc().SetCompatibilityVersion 
 (CompatibilityVersion.Version_2_2);
    }

    // This method gets called by the runtime. Use this method to configure 
the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            // The default HSTS value is 30 days. You may want to change 
this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseCookiePolicy();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Account}/{action=Login}/{id?}");
        });
        app.UseAuthentication();
    }
  }
}

Controller:

namespace Blog3Prog.Controllers
{
public class AccountController : Controller
{

    public readonly UserManager<ApplicationUser> _userManager;
    public readonly SignInManager<ApplicationUser> _signInManager;
    public readonly Models.BlogContext _context;

    public AccountController(UserManager<ApplicationUser> userManager
                            ,SignInManager<ApplicationUser> signInManager
                            , Models.BlogContext context)
    {
        _userManager = userManager;
        _signInManager = signInManager;
        _context = context;

    }
    [HttpGet]
    public IActionResult Register()
    {

        return View();
    }

    [HttpPost]
    public async Task<IActionResult> Register(RegisterViewModel vModel)
    {
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser { UserName = vModel.UserEmail, Email = vModel.UserEmail };
            var result = await _userManager.CreateAsync(user, vModel.Password);
            if (result.Succeeded)
            {
                //await _signInManager.SignInAsync(user, false);
                //return RedirectToAction("Index", "Home");
            }
            else
            {
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError("", error.Description);
                }
            }
        }
        return View(vModel);
    }



    public IActionResult Login()
    {
        return View("Login");
    }
  }
}   

View

<h2>Registration Page</h2>

<form method="post" asp-controller="Account" asp-action="Register">
<div asp-validation-summary="All"></div>
<div>
    <label asp-for="UserEmail"></label>
    <input asp-for="UserEmail" />
    <span asp-validation-for="UserEmail"></span>
</div>
<div>
    <label asp-for="Password"></label>
    <input asp-for="Password" />
    <span asp-validation-for="Password"></span>
</div>
<div>
    <label asp-for="ConfirmPassword"></label>
    <input asp-for="ConfirmPassword" />
    <span asp-validation-for="ConfirmPassword"></span>
</div>
<div>
    <input type="submit" value="Register" />
</div>


</form>

ApplicationUser.cs

using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Blog3Prog.Models
{
  public class ApplicationUser:IdentityUser
  {
    public int UserId { get; set; }
    public string UserEmail { get; set; }
    public DateTime CreatedOn { get; set; }
    public int Points { get; set; }
  }
}
1
Try changing services.AddDbContext<DbContext>(options => to services.AddDbContext<BlogContext>(options =>Matt.G
This gives me the error message: "There is no implicit reference conversion from 'Blog3Prog.Models.BlogContext' to 'Microsoft.EntityFrameworkCore.DbContext'."JimmyBoy1900
BlogContext class should be deriving from DBContext. Like public class BlogContext: DBContextMatt.G
I made this change, unfortunately this didnt solve the issue. However now when i try to add a migration i get the message: "More than one DbContext was found. Specify which one to use" When I specify which one to use by typing: " add-migration 190326-1412 -context BlogContext" i get: "Unable to create an object of type 'BlogContext'." Not sure if that helps at all? ""JimmyBoy1900
Delete these lines: services.AddScoped<BlogContext>(); services.AddScoped<DbContext>();Matt.G

1 Answers

0
votes

This gives me the error message: "There is no implicit reference conversion from 'Blog3Prog.Models.BlogContext' to 'Microsoft.EntityFrameworkCore.DbContext'.

This behavior was appeared because of BlogContext had not inherited IdentityDbContext

Here is my example below. This sample works at my local. Change User with your ApplicationUser and add your another models.

public class BlogContext : IdentityDbContext<User>
    {
        public BlogContext(DbContextOptions options) : base()
        {

        }
        public DbSet<User> Users { get; set; }
    }

public class User:IdentityUser
    {
    }

This should be added to Configure Services method.

services.AddDbContext<BlogContext>(options =>
                options.UseSqlServer("Your connection string");

I think creation of db context like you did it is a bad idea.

Also delete next from your startup:

services.AddScoped<BlogContext>();
services.AddScoped<DbContext>();

There is how can be refactored your BlogContext.cs:

public class BlogContext : IdentityDbContext<ApplicationUser>
    {
        public BlogContext(DbContextOptions options) : base()
        {

        }

        public DbSet<Message> Messages { get; set; }
        public DbSet<Timeline> Timelines { get; set; }
        public DbSet<ApplicationUser> applicationUsers { get; set; }
        public DbSet<IdentityUserClaim<Guid>> IdentityUserClaims { get; set; }
        public DbSet<IdentityUserClaim<string>> IdentityUserClaim
        {
            get;
            set;
        }

    }