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; }
}
}
services.AddDbContext<DbContext>(options =>
toservices.AddDbContext<BlogContext>(options =>
– Matt.GBlogContext
class should be deriving fromDBContext
. Likepublic class BlogContext: DBContext
– Matt.Gservices.AddScoped<BlogContext>(); services.AddScoped<DbContext>();
– Matt.G