Although it is very late to answer this question, but here it is for the future visits:
Create view model class:
public class UserViewModel
{
public string Username { get; set; }
public string Email { get; set; }
public string Role { get; set; }
}
Then populate this view model class in controller:
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();
Here, context.Users
represents the AspNetUsers
table which has a navigation property Roles
which represents the AspNetUserInRoles
table. Then we perform join of context.Roles
which represents the AspNetRoles
table to get the role name.
Now return this list to your Index view:
return View(userWithRoles);
In the view show the list of users with roles:
@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>
Edit: To get multiple roles of user(if assigned any)
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
should haveRoles
property for eachuser
:var usersWithRoles = context.Users.Select(x => new UserWithRolesViewModel {User = x, UserRoles = x.Roles}).ToList();
– Carolynncarolynne