0
votes

I am trying to populate a view model with User data that includes a list of the user's associated roles. Currently, my method is as follows:

[EnableQuery]
[AcceptVerbs("GET")]
public IEnumerable<UserViewModel> Get()
{
    var clientId = this.GetClientId();
    var users = this.UserManager.Users.Where(x => x.ClientId == clientId).ProjectTo<UserViewModel>().ToList();

    foreach (UserViewModel user in users)
    {
        user.UserRoles = this.UserManager.GetRoles(user.Id);
    }

    return users;
}

Is there a better way to perform this operation? I cannot create a Linq query because EF will not allow me to create a class for the AspNetUserRoles table, and it will not allow me to edit the AspNetUsers table directly - so I am using the UserManager to get the results instead.

You don't need to create classes - they already exist. var myUsersAndRoles = context.Users.Include(u => u.Roles).ToList(); - Steve Greene
i second @SteveGreene - Mostafa
Thank you @SteveGreene, that is exactly what I was looking for! I can mark your response as an answer if you'd like to submit the same post but as an answer :) - Brandon Hyder