SimpleMembership MVC 4 get data from UserProfile having role in webpages_Roles

asp.net-mvc asp.net-mvc-4 entity-framework

Question

I have the following code. But there must be a more database efficient way to do this, because, correct me if Im wrong the number of database queries is (1 + (qty of users with admin role))

With a new MVC 4 project the membership defaults are the tables UserProfile, webpages_Roles and webpages_UsersInRoles. I see lots of built in methods for Roles.Get*. If I want to avoid writing code like what I have below do I need to explicitly create a model for webpages_Roles and webpages_UsersInRoles as well as all the code first properties? Getting just the username from Roles.Get* doesnt suffice, I need the full UserProfile.

FYI the "UserRole" object below is just an enum

public ActionResult Admins()
    {
        var dbContext = new UsersContext();
        var usernames = Roles.GetUsersInRole(UserRole.SiteAdministrator.ToString());
        var adminUsers = new List<UserProfile>();
        foreach (string username in usernames)
        {
            var adminUser = dbContext.UserProfiles.FirstOrDefault(u => u.UserName.ToLower() == username);
            adminUser.Roles.Add(UserRole.SiteAdministrator);
            adminUsers.Add(adminUser);
        }

        return View(adminUsers);
    }
1
2
9/19/2012 10:57:53 PM

Accepted Answer

Yes, you don't want to do it that way. That's a very inefficient way.

Instead, use the tools as they were designed. For example, something like this:

var usernames = Roles.GetUsersInRole(UserRole.SiteAdministrator.ToString());

var adminUsers = dbContext.UserProfiles
     .Where(x => usernames.Contains(x.Username)).ToList();

return View(adminUsers);
5
9/21/2012 3:54:07 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow