Retrieving Users and Associated Roles in .NET Core 2.1 Identity
Many projects require a user management feature to manage and display users and their associated roles. However, obtaining this information may not be straightforward.
Solution:
Initially, utilizing the IdentityUser's Roles property was common, but it has been removed in .NET Core. One approach based on recent community suggestions involves introducing additional classes and modifying the database structure.
Modified Database Structure:
Introducing the following classes:
Extending ApplicationUser with a UserRoles property and references to the new classes.
DbContext Modifications:
Startup Identity Configuration:
Eager Loading for User Roles:
Finally, when retrieving users, eagerly load the UserRoles and their associated Roles:
this.Users = userManager.Users.Include(u => u.UserRoles).ThenInclude(ur => ur.Role).ToList();
ASP Core 2.2 Considerations:
By following this approach, you can effectively retrieve users and their associated roles in .NET Core 2.1 Identity.
The above is the detailed content of How to Efficiently Retrieve Users and Their Roles in .NET Core 2.1 Identity?. For more information, please follow other related articles on the PHP Chinese website!