This is my AccounController.cs code
private readonly UserManager<IdentityUser> _userManager;
private readonly SignInManager<IdentityUser> _signInManager;
public AccountController(UserManager<IdentityUser> userManager, SignInManager<IdentityUser> signInManager)
{
_userManager = userManager;
_signInManager = signInManager;
}
and my login code in AccountController.cs
[HttpPost]
public async Task<IActionResult> Login(LoginViewModel model, string returnUrl)
{
if (ModelState.IsValid)
{
var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, isPersistent: false, lockoutOnFailure: false); if (result.Succeeded)
{
return RedirectToAction("Index", "ArrangeType");
}
}
ModelState.AddModelError("", "Invalid ID or Password");
return View(model);
}
When I have run my application this types of error has been occured.
An unhandled exception occurred while processing the request.
InvalidOperationException: Cannot create a DbSet for 'IdentityRole' because this type is not included in the model for the context.
Microsoft.EntityFrameworkCore.Internal.InternalDbSet<TEntity>.get_EntityType()
Answer
Option 1.
Added this and it worked:
builder.Entity<IdentityUserRole<Guid>>().HasKey(p => new { p.UserId, p.RoleId });
Option 2.
The most common reasons for
- The model name does not match with the table name in database
- EntityFramework cannot figure out required meta by convention and you have not overriden it.
- AppDbContext is NOT inherited from DbContext but instead it should be inherited from IdentityDbContext<ApplicationUser>
- In accountcontroller.cs and startup.cs model doest not match then this types of issue has been occured for example
public class Role : IdentityRole
{
}
in your DbContext.cs
public class DataContext : IdentityDbContext<ApplicationUser, Role, string, IdentityUserClaim<string>, IdentityUserRole<string>,
IdentityUserLogin<string>, IdentityRoleClaim<string>, IdentityUserToken<string>>
{
public DbSet<Role> Role { get; set; }
public DataContext(DbContextOptions<DataContext> options)
: base(options)
{
}
}
in your startup.cs
services.AddIdentity<IdentityUser, IdentityRole>();
In the given above there is different Role model so this is not working.You can change startup.cs call
replace
services.AddIdentity<IdentityUser, IdentityRole>()
to
services.AddIdentity<IdentityUser, Role>()
because you have add Role class in your DataContext
Option 3.
Check that your AppDbContext is NOT inherited from DbContext but instead it should be inherited from IdentityDbContext<ApplicationUser>
Comments