无法将类型为Entity的对象强制转换为类型ActivityParty

时间:2015-03-24 00:54:05

标签: plugins dynamics-crm

我正在使用CRM online 2015的自定义插件,每次我尝试从“Email.To ”访问活动对象时,我都会

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

以下是我的代码的样子:

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)

          }
    }

}

我是否必须为activityparty类型进行一些初始化?

1 个答案:

答案 0 :(得分:2)

代码没有问题,字段Email.To将返回EntityCollection并获取您需要使用的内容:

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

这将为您提供需要转换为ActivityParty(entityCollection.Entities)的实体集合。 要转换您需要的实体:

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);            
   }
相关问题