linq to sql check for role in many to many relationship

I am not using membership provider

I have 3 tables

User, Role, UserRole

User -            UserID, Name
Role -             RoleID, RoleName
UserRole -     UserID, RoleID

I have 3 roles
Admin, TeamAdmin, User

In linq to sql I am getting the logged in user and now need to check if they are in roles and then assign a bool to say which role they are in

bool IsUserAdmin
bool IsUserTeamAdmin
bool User

What is the best way in linq to sql to get the user and check if they are in one or both roles?

Who is Participating?
You can do this in Linq query.. but I can give a different approach.

once user logged in, get all the user roles from the Table

LinkedList<String> foundRoles = from userRole in context.UserRole
                                                    join roles in contect.Role
                                                         on userRole.RoleID equals roles.RoleID
                                                    where userRole.userID == userID
                                                    select roles.RoleName;

So now you can easily check what kind of role user has, or create a method to check this for you.

public bool IsUserInRole(string roleName)
    return foundRoles.Any(c => c.Contains(roleName));

now you can assign the boolean variables

bool IsUserAdmin = IsUserInRole("Admin");
bool IsUserTeamAdmin = IsUserInRole("TeamAdmin");
bool User = IsUserInRole("User");

If you are trying to use custom role provider and your own authentication/authorization methods.. look at this post:

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.