So I've been searching Google and SO. Feels like this question has been asked many times, but no answer has helped me but I feel like I'm getting close. However, I'm new to LINQ and Lambda and don't have the knowledge to do what I want.
Desired Result
User Roles
-----------------------------------------
John Admin
Jane Staff, HR, Payroll
MyCoolUserName User
I got pretty close from this post and this post. Here's what I got so far.
ViewModel:
public class UsersViewModel {
[Display(Name = "User")]
public ApplicationUser User { get; set; }
[Display(Name = "Roles")]
public string Roles { get; set; }
}
Controller:
Trial #1
This solution returns blanks for the roles, and I had to add this to my web.config
file: <roleManager enabled="true" />
public class UsersController : Controller {
public async Task Index() {
var allUsers = await db.Users.ToListAsync();
var users = new List();
foreach (var user in allUsers) {
String[] roles = Roles.GetRolesForUser(user.UserName);
users.Add(new UsersViewModel {User = u, Roles = String.Join(",", roles.ToArray())});
}
return View(users);
}
}
Trial #2
This solution returns one row per user per role, but only returns the RoleId
public class UsersController : Controller {
public async Task Index() {
var allUsers = await db.Users.ToListAsync();
var users = allUsers.Select(u => new UsersViewModel {User = u, Roles = String.Join(",", u.Roles.Select(r => r.RoleId))}).ToList();
return View(users);
}
}
Here's what I get for Trial #2 when I change RoleId
to RoleName
:
I can tell that in trial #2, u.Roles
is linked to the UserRoles
table. Logically, I know that what I want is to inner join the Roles
table and get the name there.
I hope someone can help me out? Thanks in advance. Sample Project