Dynamics 365 ExecuteMultipleRequest

In Dynamics 365, we can use ExecuteMultipleRequest message to execute multiple requests at once as bulk.

There are times that you need to update multiple records that fits a condition, creating new records for a new business request or deleting records. The first thing comes in your mind would be, put all the records inside a for loop and iterate through them, process each record one by one. This would waste so much time because you will have to wait for each request to completed before you jump to next one.

With ExecuteMultipleRequest you can save time while sendind multiple request at once, also you can decrease the load on your server.

The following code shows how to use the ExecuteMultipleRequest message.

 public void ExecuteMultipleRequestTest()
{
    var myContacts = RetrieveMigratedContacts();
    var newOwnerRef = new EntityReference("systemuser", myId);
    int bulkAmount = 0;

    var executeMultipleRequest = new ExecuteMultipleRequest()
    {
        Requests = new OrganizationRequestCollection(),
        Settings = new ExecuteMultipleSettings
        {
            ContinueOnError = false,
            ReturnResponses = false
        }
    };

    for (int i = 0; i < myContacts.Count; i++)
    {

        var contact = new Entity("contact", myContacts[i].Id);
        contact["ownerid"] = newOwnerRef;

        var updateRequest = new UpdateRequest()
        {
            Target = contact
        };
        executeMultipleRequest.Requests.Add(updateRequest);
        bulkAmount++;

        // Update as bulks of 20 records. The last batch may be lower than 20 so check that too.
        if (bulkAmount == 20 || i == myContacts.Count - 1)
        {
            service.Execute(executeMultipleRequest);

            // initialize new ExecuteMultipleRequest to reset the collection.
            executeMultipleRequest = new ExecuteMultipleRequest()
            {
                Requests = new OrganizationRequestCollection(),
                Settings = new ExecuteMultipleSettings
                {
                    ContinueOnError = false,
                    ReturnResponses = true
                }
            };
        }
    }
}
Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s