I have a regular MVC app with a standard account controller. I’ve added couple fields to UserProfile class, so now it looks like this:
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Address { get; set; }
public string Phone { get; set; }
public string FullName { get { return FirstName + " " + LastName; } }
public int GroupId { get; set; }
[ForeignKey("GroupId")]
public ICollection<Group> Groups { get; set; }
}
So, basically saying that User can be assigned to multiple groups. (And also in Group class I say that Group can contain multiple users, obviously).
Now, each user must be in a specific role. (Admin, Teacher, Student etc.)
I’ve added roles support by following a tutorial online like this:
<roleManager enabled="true" defaultProvider="SimpleRoleProvider">
<providers>
<clear/>
<add name="SimpleRoleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData"/>
</providers>
</roleManager>
<membership defaultProvider="SimpleMembershipProvider">
<providers>
<clear/>
<add name="SimpleMembershipProvider" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData" />
</providers>
</membership>
Now I want to filter all of the users by RoleName. But I do not have any way to do that.
IE. something like this. Users.Where(x=>x.RoleName=="Admin").Select(x=>x.FullName)
(Users is a property of a Group class of type ICollection<Users>). How do I get to the roles without having a class for the roles?
The asp.net membership has a static Roles class with a GetUsersInRole method, also the CurrentUser in HttpContext can tell you the roles the active user is in.
http://msdn.microsoft.com/en-us/library/system.web.security.roles.getusersinrole.aspx
http://msdn.microsoft.com/en-us/library/system.web.security.membershipuser.aspx