我正在尝试为现场 Dynamics CRM 2011 安装创建一个插件。
我已将插件注册如下:
- 消息:创建
- 主要实体:联系人
- 执行阶段:术后
- 执行方式:同步
- 执行顺序:1
插件代码如下:
public void Execute(IServiceProvider serviceProvider)
{
var pluginExecContext = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
var orgServiceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
var orgService = orgServiceFactory.CreateOrganizationService(pluginExecContext.UserId);
var orgServiceContext = new OrganizationServiceContext(orgService);
var tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
if (pluginExecContext.InputParameters.Contains("Target") &&
pluginExecContext.InputParameters["Target"] is Entity)
{
var target = (Entity)pluginExecContext.InputParameters["Target"];
if (target.LogicalName != Contact.EntityLogicalName)
return;
try
{
var customerServicesUser = orgServiceContext.CreateQuery(SystemUser.EntityLogicalName)
.Where(x => (string)x["fullname"] == "Customer Services").FirstOrDefault();
if (customerServicesUser == null)
throw new InvalidPluginExecutionException("No Customer Services user exists.");
var sendEmail = new cdi_sendemail
{
cdi_fromrecordowner = false,
cdi_contactid = new EntityReference(Contact.EntityLogicalName, pluginExecContext.PrimaryEntityId),
cdi_fromid = new EntityReference(SystemUser.EntityLogicalName, customerServicesUser.Id)
};
tracingService.Trace("PostContactCreate plug-in: Creating the cdi_sendemail entity.");
orgService.Create(sendEmail);
}
catch (FaultException<OrganizationServiceFault> ex)
{
throw new InvalidPluginExecutionException("An error occurred in the PostContactCreate plug-in.", ex);
}
catch (Exception ex)
{
tracingService.Trace("PostContactCreate plug-in: {0}", ex.ToString());
throw;
}
}
}
当我使用 pluginregistration 工具分析插件并调试故障异常时,我收到以下错误:
联系人 ID = abbc7e0a-20a0-e111-a36e-005056860004 不存在。
我有点理解,因为插件在尚未提交的 SQL 事务中执行。CRM SDK 示例中的“FollowupPlugin”也创建了一个引用实体,它声明它需要异步注册,这也是有意义的,因为这允许 SQL 事务提交。
所以我想我的问题是,如何在同步插件中创建引用实体?