简体   繁体   English

事务中的 Dynamics Crm 批量更新记录

[英]Dynamics Crm Bulk Update records in a transaction

Requirement要求

  1. I have the requirement where I want to update few fields on account and create contact for it reading data from an API.我有一个要求,我想更新帐户中的几个字段并为其创建联系人,以便从 API 读取数据。
  2. The number of records to be updated is around 100,000 so I want to要更新的记录数约为 100,000,所以我想
    use either ExecuteTransactionRequest or ExecuteMultipleRequest so that I can execute all in batches.使用 ExecuteTransactionRequest 或 ExecuteMultipleRequest 以便我可以批量执行所有操作。

Since I want the contact record to be created for the account updated I used the ExecuteTransactionRequest.由于我希望为更新的帐户创建联系人记录,因此我使用了 ExecuteTransactionRequest。

Problem -问题 -

The problem is batch size.问题是批量大小。 I have added the condition if request batch size count equals 500 then execute all the requests.如果请求批量大小计数等于 500,则我添加了条件,然后执行所有请求。 However my batch can include但是我的批次可以包括

  • Update request for account and更新帐户请求和
  • Create request for contact创建联系请求

So it may happen that the batch may not be exact 500 and it would skip the execute request.因此,批处理可能不是精确的 500,它可能会跳过执行请求。 How can I do this and make sure that contact record is created for each Updated Account correctly.如何执行此操作并确保为每个更新的帐户正确创建联系人记录。

Any help would be appreciated.任何帮助,将不胜感激。 Thanks in Advance提前致谢

Below is my code --下面是我的代码——

  var requests = new ExecuteTransactionRequest
        {
            Requests = new OrganizationRequestCollection(),
            ReturnResponses = returnResponses
        };

  foreach (var customer in customerList)
        {
            string custNo = customer.GetAttributeValue<string>("customernumber");

            // Gets customer details from another api
            var custInfo = await CustomerService.Get(custNo);

            // Update the values on customer table
             Entity cust = new Entity("account");
             cust.Id = customer.Id;
             cust["companytypecode"] = custInfo.EntityTypeCode;
             cust["companytypedescription"] = custInfo .EntityTypeDescription;
             

            var roles = custInfo.Roles.Where(c => c.RoleStatus == "ACTIVE").ToArray();
           //create contact for each account
           foreach(var role in roles)
           {
            Entity contact = new Entity("contact");
            contact["FirstName"] = role.RolePerson?.FirstName;
            contact["MiddleName"] = role.RolePerson?.MiddleNames;
            contact["LastName"] = role.RolePerson?.LastName;
            contact["AccountId"] = new EntityReference("account", customer.Id);

            CreateRequest createRequest = new CreateRequest { Target = contact };
            requests.Requests.Add(createRequest);
          }
           
            UpdateRequest updateRequest = new UpdateRequest { Target = cust };
            requests.Requests.Add(updateRequest);

            if (requests.Requests.Count == 500) // Problem is the batch size will not execute per account since it also has create request of contact. How can i make sure that each request is executed correctly
            {
                service.Execute(requests);
                requests.Requests.Clear();
            }
        }
      // For the last remaining accounts
        if (requests.Requests.Count > 0)
        {
            service.Execute(requests);

        }

Thank you for helping out.谢谢你帮忙。 I resolved this with below solution.我用下面的解决方案解决了这个问题。 Happy to be corrected.很高兴得到纠正。

        EntityCollection requestsCollection = new EntityCollection();
        foreach (var customer in customerList)
        {
            string custNo= customer.GetAttributeValue<string>("customernumber");

            
            var custInfo = await businessService.Get(custNo);

            
         Entity cust = new Entity("account");
         cust.Id = customer.Id;
         cust["companytypecode"] = custInfo.EntityTypeCode;
         cust["companytypedescription"] = custInfo .EntityTypeDescription;
         requestsCollection.Entities.Add(cust);
            
       
        var roles = custInfo.Roles.Where(c => c.RoleStatus == "ACTIVE").ToArray();
       
       foreach(var role in roles)
       {
        Entity contact = new Entity("contact");
        contact["FirstName"] = role.RolePerson?.FirstName;
        contact["MiddleName"] = role.RolePerson?.MiddleNames;
        contact["LastName"] = role.RolePerson?.LastName;
        contact["AccountId"] = new EntityReference("account", customer.Id);

        requests.Entities.Add(contact);
      }

            
            if (requestsCollection.Entities.Count > 500)
            {
                
                ExecuteBulkUpdate(requestsCollection);
                requestsCollection = new EntityCollection();
                
            }
        }
private void ExecuteBulkUpdate(EntityCollection requestsCollection)
    {
        var requests = new ExecuteTransactionRequest
    {
        Requests = new OrganizationRequestCollection(),
        ReturnResponses = returnResponses
    };
        foreach (var request in requestsCollection.Entities)
        {
            if (request.Id != Guid.Empty)
            {   
                UpdateRequest updateRequest = new UpdateRequest { Target = request };
                requests.Requests.Add(updateRequest);
            }
            else
            {
                CreateRequest createRequest = new CreateRequest { Target = request };
                requests.Requests.Add(createRequest);
            }
        }

        try
        {
            var responseForCreateRecords = (ExecuteTransactionResponse)service.Execute(requests);
            
            int i = 0;
            // Display the results returned in the responses.
            foreach (var responseItem in responseForCreateRecords.Responses)
            {
                if (responseItem != null)
                    log.LogInformation(responseItem.Results["id"].ToString());
                i++;
            }
            requests.Requests.Clear();
        }
        catch (FaultException<OrganizationServiceFault> ex)
        {
            log.LogInformation("Request failed for the {0} and the reason being: {1}",
                ((ExecuteTransactionFault)(ex.Detail)).FaultedRequestIndex + 1, ex.Detail.Message);
            throw;
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM