在 CRM 2011 中如何创建记录并将其关联到同一个 ExecuteMultipleRequest

In CRM 2011 how to create a record and associate it in the same ExecuteMultipleRequest

我正在努力寻找一种方法来使用 ExecuteMultipleRequest 创建记录并将其同时关联到其他记录。到目前为止,我只成功地首先创建了记录,然后在另一个请求中设置了我的关联。

使用此代码会抛出一个异常,它需要一个目标(之前需要提交该目标才能创建记录并获取 ID)

private AssociateRequest GetConfigurationRequest(VariableDataRequestModel receivedRequest)
{
    var configurationRelationship = new Relationship(ConfigurationRelationshipName);            
    var configurationEntities = new EntityReferenceCollection(new EntityReference[]{new EntityReference(ConfigurationEntityLogicalName,new Guid(receivedRequest.ConfigurationId))});                        
    var rtn = new AssociateRequest() {  RelatedEntities = configurationEntities, Relationship = configurationRelationship };
    return rtn;
}

使用 ExecuteMultipleRequest 实现的唯一方法是在创建记录之前指定新记录的 Id:

Guid accountId = new Guid("c85dca5d-6520-4436-a5f6-178b633af819");

Entity myAccount = new Entity("account");
myAccount["name"] = "TEST ACCOUNT";
entity.Id = accountId;
// ...
EntityReferenceCollection relatedEntities = new EntityReferenceCollection();
relatedEntities.Add(new EntityReference("account", accountId));

允许但不建议指定Id

您可以做的另一件事是在 ExecuteMultipleRequest 中提交记录,然后在 ExecuteMultipleResponse 中获取 GUID,然后您可以使用该 GUID 和您创建的 Record 来执行 AssociateRequest。

示例:

ExecuteMultipleResponse response = (ExecuteMultipleResponse)service.Execute(updateCRM);

List<Entity> addedRecordList = new List<Entity>();

foreach (ExecuteMultipleResponseItem item in response.Responses)
{
    Guid responseReturnedGuid = (Guid)item.Response.Results.Values.FirstOrDefault(x => x is Guid);
    if (responseReturnedGuid != Guid.Empty || responseReturnedGuid != null)
    {
        Entity addedRecord = (Entity)updateCRM.Requests[item.RequestIndex].Parameters.Values.FirstOrDefault(x => x is Entity);
        addedRecord.Id = responseReturnedGuid;
        addedRecordList.Add(addedRecord);
    }
}