Search code examples
asp.netlinq-to-entitiesentitycollection

LINQ to Entities: query example


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.

Solution

  • 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.