CRM 2011 Plugins – Obtaining Entity Record Information

Roshan Mehta, 23 April 2013

Developers can use the IPluginExecutionContext service object to obtain contextual information from the CRM platform which is passed to the plugin at run-time. It includes details about the user who triggered the plugin event as well as transactional information handled at the platform layer. In this post, we will see which properties are available to obtain information about the record which triggered a plugin.

The IPluginExecutionContext object includes the following GUID properties:

• PrimaryEntityName
• PrimaryEntityId

The PrimaryEntityName property returns the schema name of the entity where the triggering action was executed. For example, if a user updates an Account which causes a plugin to fire, the PrimaryEntityName property would return “account”. This property is useful when writing plugins that need to execute on multiple entities.

if (context.PrimaryEntityName.Equals("contact", StringComparison.InvariantCultureIgnoreCase))
{
    // do something for contacts
}
else if (context.PrimaryEntityName.Equals("account", StringComparison.InvariantCultureIgnoreCase))
{
    // do something else for accounts
}

There is also a SecondaryEntityName property which is useful when defining plugin steps on the SetRelated message.

The PrimaryEntityId property returns the GUID of the record where the triggering action was executed. This property is useful when you need to retrieve the record from the CRM database.

Entity contact = _sdk.Retrieve("contact", context.PrimaryEntityId, new ColumnSet("firstname", "lastname", "emailaddress1"));

As I mentioned above, a plugin could be triggered to run on records for multiple entities. You wouldn’t normally hardcode the entity schema name in Retrieve operations so it is best to use the two properties together. For example:

Entity record = _sdk.Retrieve(context.PrimaryEntityName, context.PrimaryEntityId, new ColumnSet(true));

In my next post, we will look at how we can identify plugin execution flow and avoid infinite loops.