June 8, 2014

Retrieve the members of a specific Team

The code to retrieve the members of a specific Team is quite easy, it's a standard QueryExpression, but contains a linked entity with a condition inside, it's good as start point for similar queries.
// Id of the specific Team
Guid teamId = new Guid("DAC1F09E-02EF-E311-A2AB-D89D67630DBC");
// main query returing users
QueryExpression userQuery = new QueryExpression("systemuser");
// take all columns
userQuery.ColumnSet = new ColumnSet(true);
// this is the intersect condition
LinkEntity teamLink = new LinkEntity("systemuser", "teammembership", "systemuserid", "systemuserid", JoinOperator.Inner);
// this is the condition to use the specific Team
ConditionExpression teamCondition = new ConditionExpression("teamid", ConditionOperator.Equal, teamId);
// add the condition to the intersect
teamLink.LinkCriteria.AddCondition(teamCondition);
// add the intersect to the query
userQuery.LinkEntities.Add(teamLink); 
//get the results
EntityCollection retrievedUsers = service.RetrieveMultiple(userQuery);
// fetch the results
foreach (Entity user in retrievedUsers.Entities)
{
    // Id of the user
    var userId = user.Id;
    // FullName of the user 
    var userFullName = user.Contains("fullname") ? user["fullname"].ToString() : "";
}

2 comments:

  1. Hii, i still didte get it on this line:

    LinkEntity teamLink = new LinkEntity("systemuser", "teammembership", "systemuserid", "systemuserid", JoinOperator.Inner);

    there is linkfromattribute and linktoattribute which has same value. When i use custom entity, and i want to do sql query like this:

    SELECT user.name, order.id from order inner join on user.id = order.id

    so in the linkentities i can write like :

    LinkEntity link= new LinkEntity("user", "order", "user.id", "order.id", JoinOperator.Inner);

    What if we dont even know which field on the custom entity is the primary key. How do we know the primary key of the entity?

    Actually this i posted my problem on community.microsoft forum, but i had't get the answer

    https://community.dynamics.com/crm/f/117/t/181404

    ReplyDelete
    Replies
    1. don't try to convert queries from SQL to QueryExpression, you start from the query you want to have and build the QueryExpression. In this particular case we have the standard N:N relationship "teammembership" that because is a standard N:N it contains the primary keys of both entities involved, teamid and systemuserid, so we link the systemuser table and teammembership table using systemuserid in both table (and put the condition to teamid on the linkcriteria that belongs to the teammembership entity

      Delete