robert_rg
robert_rg

Reputation: 297

Cannot create a DbSet for 'IdentityUser' because this type is not included in the model for the context

Trying to all code to get all users with their roles so I had to change up my code a bit and ran into this error. I'm not sure what I did wrong, I narrowed it down to my startup.cs and ApplicationDBContect class. I have no errors, and I might need a migration, haven't done that to prevent causing more issues.

I reference Stackoverflow question and had other errors.

ApplicationDBContext.cs

public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string, IdentityUserClaim<string>,
ApplicationUserRole, IdentityUserLogin<string>,
IdentityRoleClaim<string>, IdentityUserToken<string>>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
       : base(options)
    {
    }
    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);

        builder.Entity<ApplicationUserRole>(userRole =>
        {
            userRole.HasKey(ur => new { ur.UserId, ur.RoleId });

            userRole.HasOne(ur => ur.Role)
                .WithMany(r => r.UserRoles)
                .HasForeignKey(ur => ur.RoleId)
                .IsRequired();

            userRole.HasOne(ur => ur.User)
                .WithMany(r => r.UserRoles)
                .HasForeignKey(ur => ur.UserId)
                .IsRequired();
        });
    }

    public DbSet<ApplicationUser> ApplicationUser { get; set; }
}

Startup.cs

services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(
                Configuration.GetConnectionString("DefaultConnection")));

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

Upvotes: 6

Views: 16769

Answers (1)

TanvirArjel
TanvirArjel

Reputation: 32059

I see you are extending both IdenityUser and IdentityRole with ApplicationUser and ApplicationRole respectively but you did not add them in your identity service registration. So update your identity service registration in startup as follows:

services.AddIdentity<ApplicationUser, ApplicationRole>() // </-- here you have to replace `IdenityUser` and `IdentityRole` with `ApplicationUser` and `ApplicationRole` respectively
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultUI()
            .AddDefaultTokenProviders();

Upvotes: 10

Related Questions