Trying to display users along with their role in core 2.1, I followed the example stackoverflow . I have no errors but I'm not getting user roles to display. I think it could be my view, for some reason my code returns an email address instead of user role.
ApplicationDbContext
public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string, IdentityUserClaim<string>, ApplicationUserRole, IdentityUserLogin<string>, IdentityRoleClaim<string>, IdentityUserToken<string>>{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}protected override void OnModelCreating(ModelBuilder builder) { base.OnModelCreating(builder); builder.Entity<ApplicationUserRole>(userRole => { userRole.HasKey(ur => new { ur.UserId, ur.RoleId }); userRole.HasOne(ur => ur.Role) .WithMany(r => r.UserRoles) .HasForeignKey(ur => ur.RoleId) .IsRequired(); userRole.HasOne(ur => ur.User) .WithMany(r => r.UserRoles) .HasForeignKey(ur => ur.UserId) .IsRequired(); }); } public DbSet<ApplicationUser> ApplicationUser { get; set; }
}
Startup.cs
services.AddIdentity<ApplicationUser, ApplicationRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultUI()
.AddDefaultTokenProviders();
ApplicationUser
public class ApplicationUser : IdentityUser
{
public ICollection<ApplicationUserRole> UserRoles { get; set; }public class ApplicationUserRole : IdentityUserRole<string> { public virtual ApplicationUser User { get; set; } public virtual ApplicationRole Role { get; set; } } public class ApplicationRole : IdentityRole { public ICollection<ApplicationUserRole> UserRoles { get; set; } }
}
Index method:
public async Task<IActionResult> Index(int? page )
{
var users = from u in _userManager.Users.Include(u => u.UserRoles).ThenInclude(ur => ur.Role) select u;return View(users.ToPagedList(pageNumber, pageSize));
}
View
@Html.DisplayFor(m => item.UserRoles)
#asp.net