Home > Blockchain >  How do I query a user's teams in Dynamics 365 C# plugin?
How do I query a user's teams in Dynamics 365 C# plugin?

Time:03-07

The example shown here passes in the userID and a string array of security names. Then return true if the user has any security roles that match the names.

public static bool UserHasRoles(IOrganizationService service, Guid userId, params string[] roleNames)
{
        var query = new QueryExpression("systemuserroles");
        query.TopCount = 1; 
        query.ColumnSet.AddColumns("systemuserroleid");           
        query.Criteria.AddCondition("systemuserid", ConditionOperator.Equal, userId);
        
        var query_role = query.AddLink("role", "roleid", "roleid");            
        query_role.LinkCriteria.AddCondition("name", ConditionOperator.In, roleNames);
        
        var result = service.RetrieveMultiple(query);
        return result.Entities.Any();
}

I need to recreate this code but to return true if the user is part of any teams that contain the same names. Below is my attempt:

public static bool UserHasRoles(IOrganizationService service, Guid userId, params string[] roleNames)
{
        var query = new QueryExpression("teammembership");
        query.TopCount = 1; 
        query.ColumnSet.AddColumns("teamMembershipId");           
        query.Criteria.AddCondition("systemuserid", ConditionOperator.Equal, userId);

        var query_role = query.AddLink("team", "teamid", "teamid");
        query_role.LinkCriteria.AddCondition("name", ConditionOperator.In, roleNames);
        
        var result = service.RetrieveMultiple(query);

        return result.Entities.Any();
}

When ran the code, I get an error

'TeamMembership' entity doesn't contain attribute with Name = 'teamMembershipId' and NameMapping = 'Logical'

I'm unsure if I am querying the equivalent entity correctly. Or I may be going about this in completely the wrong way. Help would be great.

CodePudding user response:

Actually, you don't need any column to be returned.
Here's your code without ColumnSet line, also I've corrected your method name and parameter name:

public static bool UserInTeams(IOrganizationService service, Guid userId, params string[] teamNames)
{
    var query = new QueryExpression("teammembership");
    query.TopCount = 1;
    query.Criteria.AddCondition("systemuserid", ConditionOperator.Equal, userId);
    
    var query_role = query.AddLink("team", "teamid", "teamid");
    query_role.LinkCriteria.AddCondition("name", ConditionOperator.In, teamNames);
    
    var result = service.RetrieveMultiple(query);
    return result.Entities.Any();
}
  • Related