Getting .NET Core 2.1 Identity Users and Associated Roles
In .NET Core Identity, retrieving users and their associated roles can be challenging. While earlier versions of Identity provided a built-in Roles property within ApplicationUser, this feature is no longer present.
Solution
To address this issue, implement the following solution:
ApplicationUser
public class ApplicationUser : IdentityUser { public ICollection<ApplicationUserRole> UserRoles { get; set; } }
ApplicationUserRole
public class ApplicationUserRole : IdentityUserRole<string> { public virtual ApplicationUser User { get; set; } public virtual ApplicationRole Role { get; set; } }
ApplicationRole
public class ApplicationRole : IdentityRole { public ICollection<ApplicationUserRole> UserRoles { get; set; } }
ApplicationDbContext (added relationships, configured seed)
public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string, IdentityUserClaim<string>, ApplicationUserRole, IdentityUserLogin<string>, IdentityRoleClaim<string>, IdentityUserToken<string>> { public DbSet<ApplicationUserRole> UserRoles { get; set; } // migrations omitted for brevity }
Startup
services.AddIdentity<ApplicationUser, ApplicationRole>(options => options.Stores.MaxLengthForKeys = 128) .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders();
Razor Page Code (eagerly load related data)
this.Users = userManager.Users.Include(u => u.UserRoles).ThenInclude(ur => ur.Role).ToList();
ASP Core 2.2 Update
For ASP Core 2.2 and above, inherent from IdentityUserRole
I tried to follow a suggested solution, but it resulted in the error: 'Unknown column 'u.Roles.ApplicationUserId' in 'field list''. To resolve this, I researched a GitHub comment/issue and implemented the solution outlined above. The key modifications involved creating new ApplicationUserRole and ApplicationRole classes, updating the ApplicationUser class to reflect the new relationship, and adding a custom configuration to the model builder in the DbContext. By eager loading the User's UserRoles and then the UserRole's Role, I was able to successfully retrieve the users and their associated roles.
The above is the detailed content of How to Efficiently Retrieve .NET Core 2.1 Identity Users and Their Associated Roles?. For more information, please follow other related articles on the PHP Chinese website!