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?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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:


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.