Retrieve the Roles for a User

This sample shows how to build a QueryExpression to for use with RetrieveMultiple to find all the roles for a user. To do this, you have to build a query for roles where you join 'role' to 'systemuserroles', and then join systemuserroles' to 'systemuser' and add a condition where systemuser.systemuserid equals the attribute UserId.




// Retrieve the GUID of the logged on user.
WhoAmIRequest whoReq = new WhoAmIRequest();
WhoAmIResponse whoResp = (WhoAmIResponse) service.Execute(whoReq);
Guid userid = whoResp.UserId;

// Create a QueryExpression.
QueryExpression qe = new QueryExpression();
qe.EntityName = "role";
// Be aware that using AllColumns may adversely affect
// performance and cause unwanted cascading in subsequent
// updates. A best practice is to retrieve the least amount of
// data required.
qe.ColumnSet = new AllColumns();

// Set up the join between the role entity
// and the intersect table systemuserroles.
LinkEntity le = new LinkEntity();
le.LinkFromEntityName = "role";
le.LinkFromAttributeName = "roleid";
le.LinkToEntityName = "systemuserroles";
le.LinkToAttributeName = "roleid";

// Set up the join between the intersect table
// systemuserroles and the systemuser entity.
LinkEntity le2 = new LinkEntity();
le2.LinkFromEntityName = "systemuserroles";
le2.LinkFromAttributeName = "systemuserid";
le2.LinkToEntityName = "systemuser";
le2.LinkToAttributeName = "systemuserid";

// The condition is to find the user ID.
ConditionExpression ce = new ConditionExpression();
ce.AttributeName = "systemuserid";
ce.Operator = ConditionOperator.Equal;
ce.Values = new object[]{userid};

le2.LinkCriteria = new FilterExpression();
le2.LinkCriteria.Conditions = new ConditionExpression[]{ce};

le.LinkEntities = new LinkEntity[]{le2};
qe.LinkEntities = new LinkEntity[]{le};

// Execute the query.
BusinessEntityCollection bec = service.RetrieveMultiple(qe);