C# Code for Assigning Security Role to a User – CRM 2011/2013/2015/2016


Today we got a requirement to assign Security Role to a user. We all know that Security Roles are associated with User via N:N relationship and relationship name is systemuserroles_association.

We can use AssociateRequest to assign the security roles to the user programmatically.

Here is the C# code for assigning a security role to a user.

public void AssignSecurityRole(Guid guidSystemUserId, Guid guidSecurityRoleId, IOrganizationService crmService)
        // Create new Associate Request object for creating a N:N relationsip between User and Security
        AssociateRequest objAssociateRequest = newAssociateRequest();
        // Create related entity reference object for associating relationship
        // In this case we SystemUser entity reference  
        objAssociateRequest.RelatedEntities = new EntityReferenceCollection();
        objAssociateRequest.RelatedEntities.Add(new EntityReference(“systemuser”, guidSystemUserId));
        // Create new Relationship object for System User & Security Role entity schema and assigning it 
        // to request relationship property
        objAssociateRequest.Relationship = new Relationship(“systemuserroles_association”);
        // Create target entity reference object for associating relationship
        objAssociateRequest.Target = new EntityReference(“role”, guidSecurityRoleId);
        // Passing AssosiateRequest object to Crm Service Execute method for assigning Security Role to User

Hope this helps.

Happy CRM’ing


Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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