无法将实体类型的对象转换为类型 ActivityParty

Unable to cast object of type Entity to Type ActivityParty

我正在使用 CRM online 2015 的自定义插件,每次我尝试从字段 "Email.To" 访问 activityparty 时,我都会得到

"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)

          }
    }

}

我必须对活动方类型进行一些初始化吗?

代码没有问题,字段 Email.To 将 return 一个 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);            
   }