0

Can I get a list of all the users with the associated roles in .Net Core 3.1 from Identity? I haven't found any solution that works.

jps
  • 20,041
  • 15
  • 75
  • 79
Paolo Constantin
  • 745
  • 1
  • 5
  • 4

1 Answers1

0

You need to customize Identity Model and add navigation properties.

public class ApplicationUser : IdentityUser
{
    public virtual ICollection<ApplicationUserRole> UserRoles { get; set; }
}

and then add required configuration.

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);


    modelBuilder.Entity<ApplicationUser>(b =>
    {
        // Each User can have many entries in the UserRole join table
        b.HasMany(e => e.UserRoles)
            .WithOne(e => e.User)
            .HasForeignKey(ur => ur.UserId)
            .IsRequired();
    });

    modelBuilder.Entity<ApplicationRole>(b =>
    {
        // Each Role can have many entries in the UserRole join table
        b.HasMany(e => e.UserRoles)
            .WithOne(e => e.Role)
            .HasForeignKey(ur => ur.RoleId)
            .IsRequired();            
    });
}

and then you can use joins to query users with roles. More information on adding navigation proprieties can be found here

Mujahid Daud Khan
  • 1,983
  • 1
  • 14
  • 23