I have default project template of ASP.NET MVC 5 web site and I am trying to list all users with role names (not IDs).
The query is:
db.Users.Include(u =
Thanks to @Callum Linington for his answer. Just Try to make it little bit clear for beginners like me. Here is steps to get a list of users with their roles.
1- Create a view model called "UsersWithRoles" with some properties as shown below :
2- Create a controller called "RolesController", and then add following piece of code in it.
public ActionResult Index()
{
using (var context = new ApplicationDbContext())
{
var sql = @"
SELECT AspNetUsers.UserName, AspNetRoles.Name As Role
FROM AspNetUsers
LEFT JOIN AspNetUserRoles ON AspNetUserRoles.UserId = AspNetUsers.Id
LEFT JOIN AspNetRoles ON AspNetRoles.Id = AspNetUserRoles.RoleId";
//WHERE AspNetUsers.Id = @Id";
//var idParam = new SqlParameter("Id", theUserId);
var result = context.Database.SqlQuery(sql).ToList();
return View(result);
}
}
and here is what the RolesController should look like :
3- Add Index page to Roles folder, and add the following code in it.
@model IEnumerable
Users
User Name
Role
@foreach (var user in Model)
{
@user.UserName
@user.Role
}
Here is the result
Thanks.