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.
Asked
Active
Viewed 338 times
0
-
2Can you show what you have tried, and how it didnt work. – TheGeneral Jul 17 '20 at 05:56
-
Yes, i tried this one: https://stackoverflow.com/questions/51004516/net-core-2-1-identity-get-all-users-with-their-associated-roles?answertab=oldest#tab-top – Paolo Constantin Jul 17 '20 at 15:08
1 Answers
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