尝试显示用户及其在核心2.1中的角色,我遵循了示例stackoverflow。我没有错误,但是没有显示用户角色。我认为这可能是我的观点,出于某种原因,我的代码返回的是电子邮件地址,而不是用户角色。
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; }
}
}
索引方法:
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));
}
查看
@Html.DisplayFor(m => item.UserRoles)
答案 0 :(得分:1)
您将所有内容放入ApplicatonUser
类中。首先,如下重新排列模型类:
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; }
}
现在UserRoles
是一个集合,您不能用@Html.DisplayFor(m => item.UserRoles)
显示此集合,而是必须按照以下步骤遍历该集合:
@model List<ApplicationUser>
@{
foreach (ApplicationUser applicationUser in Model)
{
<div>UserName : @applicationUser.UserName</div>
<br/>
<h4>User's Role</h4>
<hr/>
foreach (ApplicationUserRole applicationUserRole in applicationUser.UserRoles)
{
<div>RoleName: @applicationUserRole.Role.Name</div>
}
}
}