How To Get The Target Entity In Microsoft CRM Plugins With C#

Typically you want to use the target entity in Microsoft CRM plugins to validate, calculate and/or manipulate values. By the time you register a plugin step you have to set the primary entity, which later will be your target entity.

Message and Primary Entity Settings

In your plugin code, where you implement the implementation of IPlugin, which needs a Execute method with a parameter for IServiceProvider, you now can create a instance of the IPluginExecutionContext.

IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.
GetService(typeof(IPluginExecutionContext))

With the context you now have access to all the input parameters which are transferred to the plugin.

Usually the primary entity is accessible with the key "Target" within the InputParameters List.

Entity target = null;        

if (context.InputParameters.Contains("Target"))
{
    if (context.InputParameters["Target"] is Entity)
    {
        target = (Entity)context.InputParameters["Target"];
    }
}

However, you should always make some kind of validation if the value is available and has the correct type. If so, you can parse the value to an Entity and work with it from now on.

When you are using early-bound classes you can parse the entity further to a specific kind of entity like a contact.

var contact = target.ToEntity<Contact>();

The advantage of early-bound classes is, that you can access all available properties and use auto-completion instead of accessing all properties via keys.

In the official Microsoft CRM SDK you'll find the used Plugin Registration Tool, other tools and sample code by Microsoft.