[SOLVED] InvalidOperationException: Cannot create a DbSet for 'Role' because this type is not included in the model for the context

Issue

The following solution works in .net core 1.1, but after upgrading from 1.1 to 2.0, I received the following error:

InvalidOperationException: Cannot create a DbSet for ‘Role’ because this type is not included in the model for the context.

When the user attempts to log in and the following statement is executed:

var result = await _signInManager.PasswordSignInAsync(model.Email, 
                                model.Password, model.RememberMe, lockoutOnFailure: false);

What is wrong?


User.cs

public partial class User : IdentityUser<Guid>
{
    public string Name { get; set; }
}

IdentityEntities.cs

public partial class UserLogin : IdentityUserLogin<Guid>
{
}
public partial class UserRole : IdentityUserRole<Guid>
{
}
public partial class UserClaim : IdentityUserClaim<Guid>
{
}
public partial class Role : IdentityRole<Guid>
{
    public Role() : base()
    { 
    }

    public Role(string roleName)
    {
        Name = roleName;
    }
}
public partial class RoleClaim : IdentityRoleClaim<Guid>
{
}
public partial class UserToken : IdentityUserToken<Guid>
{
}

ConfigureServices

services.AddIdentity<User, Role> 

Solution

Added this and it worked:

builder.Entity<IdentityUserRole<Guid>>().HasKey(p => new { p.UserId, p.RoleId });

Answered By – 001

Answer Checked By – Marilyn (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *