In managing users and their roles, it's crucial to have a mechanism for retrieving both efficiently. This article delves into how to accomplish this task in .NET Core 2.1 using the Identity Framework.
One common approach involves modifying the ApplicationUser class to include a Roles property. However, this is no longer supported in .NET Core. Attempts to use this implementation will result in an error when trying to include roles in the query.
To overcome this issue, a custom relationship table is required. This table will connect the ApplicationUser and IdentityRole tables, allowing us to retrieve users and their associated roles.
The following entities define this relationship:
The ApplicationDbContext must be updated to handle these entities and their relationships:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string> { protected override void OnModelCreating(ModelBuilder builder) { // Define the relationship between ApplicationUser and ApplicationUserRole builder.Entity<ApplicationUserRole>() .HasKey(ur => new { ur.UserId, ur.RoleId }); builder.Entity<ApplicationUserRole>() .HasOne(ur => ur.User) .WithMany(u => u.UserRoles) .HasForeignKey(ur => ur.UserId) .IsRequired(); builder.Entity<ApplicationUserRole>() .HasOne(ur => ur.Role) .WithMany(r => r.UserRoles) .HasForeignKey(ur => ur.RoleId) .IsRequired(); } }
To retrieve users and their associated roles, the following code is added to the Razor Page:
public IActionResult OnGetAsync() { this.Users = userManager.Users .Include(u => u.UserRoles) .ThenInclude(ur => ur.Role) .ToList(); return Page(); }
The ".Include(u => u.UserRoles)" part eagerly loads the UserRoles for each user. The ".ThenInclude(ur => ur.Role)" part further eagerly loads the Role for each UserRole. This ensures that both users and their roles are available in the model.
The above is the detailed content of How to Efficiently Retrieve Users and Their Associated Roles in .NET Core 2.1?. For more information, please follow other related articles on the PHP Chinese website!