Search code examples
pluginsdynamics-crm

Unable to cast object of type Entity to Type ActivityParty


Im working with a custom plugin for CRM online 2015 and every time I try to access the activityparty from the field "Email.To" I get

"base {System.SystemException} = {"Unable to cast object of type 'Microsoft.Xrm.Sdk.Entity' to type ...ActivityParty'."}" 

Here is how my code looks like:

public class PreCreate : Plugin
{
   public PreCreate()
        : base(typeof(PreCreate))
     {           
        base.RegisteredEvents.Add(new Tuple<int, string, string, Action<LocalPluginContext>>(20, "Create", "email", new Action<LocalPluginContext>(ExecutePreEntityCreate)));

     }

   public void ExecutePreEntityCreate(LocalPluginContext localContext)
    {

      var target = (Entity)localContext.PluginExecutionContext.InputParameters["Target"];

      using (var context = new XrmServiceContext(localContext.OrganizationService))
          {
                var email = target.ToEntity<Email>(); //The entity has the right values
                 var activityPartyList=email.To // here I see the exception

                 //If I use the following code:                         
                var activityParty = email.GetAttributeValue<EntityCollection>("to");
                 //I get an empty ActivityParty(empty Id)

          }
    }

}

Do I have to do some initialization for activityparty types?


Solution

  • There is no issue with the code, the field Email.To will return a EntityCollection and to obtain that you need to use:

    var entityCollection = email.GetAttributeValue<EntityCollection>("to");
    

    This will give you a collection of entities that need to be converted to ActivityParty(entityCollection.Entities). To convert the Entities you need to:

    foreach (var entityItem in entityCollection.Entities)
       {
           var ap = entityItem.ToEntity<ActivityParty>();
           //Here you will get the LogicalName in this case Lead
           // the Id and the name 
           var leadId = ap.PartyId.Id;
          //To get the Lead 
          var lead=context.LeadSet.FirstOrDefault(l => l.Id == leadId);            
       }