Check/Get user security role in CRM using C# Code


Sometimes, we get the requirement to check the security role of the user in code and doing some business operation.

Here is the C# code for getting security role of the user.

QueryExpression queryExpression = new QueryExpression();
queryExpression.EntityName = “role”; //role entity name
ColumnSet cols = new ColumnSet();
cols.AddColumn(“name”); //We only need role name
queryExpression.ColumnSet = cols;
ConditionExpression ce = newConditionExpression();
ce.AttributeName = “systemuserid”;
ce.Operator = ConditionOperator.Equal;
//system roles
LinkEntity lnkEntityRole = newLinkEntity();
lnkEntityRole.LinkFromAttributeName = “roleid”;
lnkEntityRole.LinkFromEntityName = “role”; //FROM
lnkEntityRole.LinkToEntityName = “systemuserroles”;
lnkEntityRole.LinkToAttributeName = “roleid”;
//system users
LinkEntity lnkEntitySystemusers = new LinkEntity();
lnkEntitySystemusers.LinkFromEntityName = “systemuserroles”;
lnkEntitySystemusers.LinkFromAttributeName = “systemuserid”;
lnkEntitySystemusers.LinkToEntityName = “systemuser”;
lnkEntitySystemusers.LinkToAttributeName = “systemuserid”;
lnkEntitySystemusers.LinkCriteria = new FilterExpression();
EntityCollection entColRoles = service.RetrieveMultiple(queryExpression);
if(entColRoles != null && entColRoles.Entities.Count > 0)
     foreach (EntityentRole in entColRoles.Entities)
         if (entRole.Attributes[“name”].ToString().ToLower() == “”)

Hope this helps.

Happy CRM’ing


2 thoughts on “Check/Get user security role in CRM using C# Code

  1. Unknown April 30, 2017 / 8:16 pm

    HI,i get an error that says the limit for the maximum number of entities to query has exceeded when I put the code in a foreach loop and pass values dynamically of userid from an array


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s