虽然回答这个问题已经很晚了,但是为了未来的访问者,我还是提供一下:
创建视图模型类:
public class UserViewModel
{
public string Username { get; set; }
public string Email { get; set; }
public string Role { get; set; }
}
然后在控制器中填充此视图模型类:
var usersWithRoles = (from user in context.Users
from userRole in user.Roles
join role in context.Roles on userRole.RoleId equals
role.Id
select new UserViewModel()
{
Username = user.UserName,
Email = user.Email,
Role = role.Name
}).ToList();
在这里,
context.Users
代表了
AspNetUsers
表,该表具有一个导航属性
Roles
,该属性代表
AspNetUserInRoles
表。然后,我们将
context.Roles
与代表
AspNetRoles
表的表进行连接以获取角色名。
现在将此列表返回到您的Index视图:
return View(userWithRoles)
在视图中展示带有角色的用户列表:
@model IEnumerable<MyProject.Models.UserViewModel>
<div class="row">
<h4>Users</h4>
@foreach (var user in Model)
{
<p>
<strong>
@user.Username | @user.Email | @user.Role
</strong>
</p>
}
</div>
编辑:获取用户的多个角色(如果分配任何角色)
var usersWithRoles = (from user in _ctx.Users
select new
{
Username = user.UserName,
Email = user.Email,
RoleNames = (from userRole in user.Roles
join role in _ctx.Roles on userRole.RoleId equals role.Id
select role.Name).ToList()
}).ToList().Select(p => new UserViewModel()
{
Username = p.Username,
Email = p.Email,
Role = string.Join(",", p.RoleNames)
});
context.Users
应该为每个user
拥有一个Roles
属性:var usersWithRoles = context.Users.Select(x => new UserWithRolesViewModel {User = x, UserRoles = x.Roles}).ToList();
- Dmitry Pavliv