Search code examples
pluginsdynamics-crmcrm

What and when can "Target" be instead of an Entity and should I check its logical name when working on a single entity type?


I'm a newbie in developing in CRM, so I want to get some things clear. And you first you need to know the reason why you have to do something in order to fully understand it. So lets get to the question.

I know you have to do this when making a plugin:

var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
if (context.InputParameters.Contains("Target") && context.InputParameters.["Target"] is Entity)
{
     var entity = (Entity)context.InputParameters["Target"];
     if(entity.LogicalName == "myEntity")
     {
         //Do something with your entity
     }
}

Now, in the PluginRegistration Tool, you can set up that your plugin will be fired on the defined Message and which entities (and specific attributes from them) will be affected by it, besides other stuff.

I can see the validations are very useful when manipulating several entities with a single plugin.

Now, let's suppose you only are updating a single entity with your plugin. Why should I check if the entity that's on "Target" is the entity I want to work on, if I already know because I set it up for that entity in particular? What can an Entity be otherwise in that scenario?

Also, in what cases "Target" is NOT an Entity (in the current context)?

Thanks in advance, and sorry if this is a silly question.


Solution

  • See this answer: Is Target always an Entity or can it be EntityReference?

    Per the SDK (https://msdn.microsoft.com/en-us/library/gg309673.aspx):

    Note that not all requests contain a Target property that is of type Entity, so you have to look at each request or response. For example, DeleteRequest has a Target property, but its type is EntityReference.

    The bottom line is that you need to look at the request (all plugin's fire on an OrganizationRequest) of which there are many derived types (https://msdn.microsoft.com/en-us/library/microsoft.xrm.sdk.organizationrequest.aspx) to determine the type for the Target property.