How to programmatically get a user with a specific role in the MS CRM business unit

I am trying to get a user with a specific role from the MS CRM 2011 business unit through the C # plugin, however, I am stuck in making the correct request for this. Roles associated with users through N:N relationships, and I'm struggling to find an example query for this case.

Now I came up with the following:

 var entity = organizationService.Retrieve(entityName, entityId, new ColumnSet(new string[] { "new_unit" })); if (entity.Attributes.Keys.Contains("new_unit")) { QueryExpression query = new QueryExpression("systemuser"); query.ColumnSet = new ColumnSet(new string[] { "systemuserid" }); query.Distinct = true; query.Criteria = new FilterExpression(); query.Criteria.AddCondition("businessunitid", ConditionOperator.Equal, ((EntityReference)entity.Attributes["new_unit"]).Id); } 

I’m not sure which object I need to connect the systemuser and how to achieve the goal, get the user with a specific role and business unit.

I can easily get the name of the role or its Guid , but what should I do next?

+4
source share
1 answer

You must use AddLink methods to perform the joins.

This should be what you need:

 QueryExpression query = new QueryExpression("systemuser"); query.ColumnSet = new ColumnSet(new string[] { "systemuserid" }); query.Distinct = true; query.Criteria = new FilterExpression(); query.Criteria.AddCondition("businessunitid", ConditionOperator.Equal, ((EntityReference)entity.Attributes["new_unit"]).Id); query.AddLink("systemuserroles", "systemuserid", "systemuserid"). AddLink("role","roleid", "roleid"). LinkCriteria.AddCondition("name", ConditionOperator.Equal, "MyRoleName"); var users = organizationService.RetrieveMultiple(query); 

And if you can easily get a RoleId, you can skip the Add link in Entity Role and just add your LinkCriteria condition to the SystemUserRoles object:

 QueryExpression query = new QueryExpression("systemuser"); query.ColumnSet = new ColumnSet(new string[] { "systemuserid" }); query.Distinct = true; query.Criteria = new FilterExpression(); query.Criteria.AddCondition("businessunitid", ConditionOperator.Equal, ((EntityReference)entity.Attributes["new_unit"]).Id); query.AddLink("systemuserroles", "systemuserid", "systemuserid"). LinkCriteria.AddCondition("roleid", ConditionOperator.Equal, roleIdGuid); var users = organizationService.RetrieveMultiple(query); 
+4
source

All Articles