0

Can someone show me how to get a user's usergroup relation in LINQ to Entities from this model?

I need get a list to be able to loop it after ward in such way:

foreach (QASModel.UserGroup usergroup in ...)

Bonus points if you can provide some examples on how to :

  • get a user's role permission "path" based on the user ID
  • get a user's role based on it's ID
  • get a all user(s) of a specific role based on the role ID that would also help.
orftz
  • 1,138
  • 13
  • 22
user706058
  • 415
  • 3
  • 11
  • 23

2 Answers2

1

I think that this is what you're looking for:

int uID = 55;    //The user ID that you're looking for

//Assumption for the data context name
QASDataContext ctx = new QASDataContext();   

//--(1)--
//Get the user's user groups
var user = (from u in ctx.Users
 where u.ID == uID
 select u).FirstOrDefault();

if(user != null)
{
    foreach(UserGroup in user.UserGroups)
    {
        //do your thing
    }

    //--(2)--
    //Get User's Role Permission Path(s)
    List<string> PermissionPaths = new List<string>();

    foreach(UserRole role in user.UserRoles)
    {
        foreach(UserRolesPer perPath in role.UserRolesPers)   //Can't see the whole table name
        {
            PermissionPaths.Add(perPath.Path);
        }
    }

    //You can use the PermissionPaths object now

    //--(3)--
    //Get a User's Role based on the User ID 
    //Use the same user object from above
    UserRole uRole = user.UserRole;
}

//--(4)--
//Get a all user(s) of a specific role based on the role ID
int myRoleID = 43;

var role = (from r in ctx.UserRoles
    where r.ID == myRoleID 
    select r).FirstOrDefault();

if(role != null)
{
    foreach(User u in role.Users)
    {
        // do something
    }
}

Please note that I didn't run this through a complier, but this should give you the basic idea of what you're looking for.

cbossie
  • 26
  • 2
0
IEnumerable<UserGroup> userGroups = from ug in context.UserGroups
                                    from u in ug.Users
                                    where u.ID == [userID]
                                    select ug;

IEnumerable<string> userRoles = from ur in context.UserRoles
                                from rps in ur.UserRolesPermissions
                                where ur.UserId == id
                                select rps.Path;

IEnumerable<User> usersFromSpecificRole = from u in context.Users
                                          where u.UserRole.ID == [roleID]
                                          select u;

Didn't have time to check so if there are any problems please let me know and I'll try and fix them.

aligray
  • 2,812
  • 4
  • 26
  • 35