4

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();
TanvirArjel
  • 30,049
  • 14
  • 78
  • 114
robert_rg
  • 275
  • 1
  • 5
  • 13

1 Answers1

8

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();
TanvirArjel
  • 30,049
  • 14
  • 78
  • 114
  • This is the answer that helped me. I had neglected to add the `services.AddIdentity()` to my `Program.cs`/`Startup.cs` file – tisaconundrum Jul 27 '22 at 23:20