Gary
Gary

Reputation: 1774

Dynamics CRM 2011 Plugin How to get the team(s) a user belongs to

I have a requirement to check and see if a user is on a specific team. I'm assuming that I have to start at the team, but I'm not really sure about that. It would easier to just look and see all the teams a user belongs to. Does anyone have an example of using a N:N relationship in a plugin?

Here is the code I have so far...

// Set the properties of the QueryExpression object.
teamQuery.EntityName = "team";
teamQuery.AddAttributeValue("name", "Team");
teamQuery.ColumnSet = teamColumnSet;

EntityCollection teamDetail = service.RetrieveMultiple(teamQuery);

foreach (var teamDetail in teamDetail.Entities)
{
    teamGuid = teamDetail.Id;
}

Thank you for the help!!

Gary

Upvotes: 2

Views: 7210

Answers (2)

Gary
Gary

Reputation: 1774

This was my final solution...

QueryExpression teamQuery = new QueryExpression("team");
ColumnSet teamColumnSet = new ColumnSet("name");

teamQuery.ColumnSet = teamColumnSet;
teamQuery.Criteria = new FilterExpression();
teamQuery.Criteria.FilterOperator = LogicalOperator.And;
teamQuery.Criteria.AddCondition("name", ConditionOperator.Equal, "Sales");
teamQuery.AddLink("teammembership", "teamid", "teamid").AddLink ("systemuser", "systemuserid", "systemuserid").LinkCriteria.AddCondition("systemuserid", ConditionOperator.Equal, salesRepGuid);

 EntityCollection teamDetail = service.RetrieveMultiple(teamQuery);

Gary

Upvotes: 7

MarioZG
MarioZG

Reputation: 2087

You can use fetchXML. This will check in one server request instead two (one to get teamid, second to check N:N relationship)

            string fetchXML = @"
<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='true'>
  <entity name='systemuser'>
    <filter type='and'>
      <condition attribute='systemuserid' operator='eq' value='{0}' />
    </filter>
    <link-entity name='teammembership' from='systemuserid' to='systemuserid' visible='false' intersect='true'>
      <link-entity name='team' from='teamid' to='teamid' alias='ai'>
        <filter type='and'>
          <condition attribute='name' operator='eq' value='{1}' />
        </filter>
      </link-entity>
    </link-entity>
  </entity>
</fetch> ";

            Guid userID; //assign userid here. 
            string teamName = "team to check";
            fetchXML = string.Format(fetchXML, userID, teamName);

            EntityCollection result = service.RetrieveMultiple(new FetchExpression(fetchXML));

            bool isUserInTeam = result.Entities.Count > 0; 

Upvotes: 1

Related Questions