ExecuteMultipleRequest in Dynamics CRM 2011

Roshan Mehta, 08 January 2013

I am excited to announce my favourite feature of the December 2012 release of Microsoft Dynamics CRM 2011 – the ExecuteMultipleRequest. This addition to the CRM SDK allows developers to create, update, and delete records in bulk for both on-premise and online deployments. In this blog, I will show you how easy it is to perform these bulk operations in your custom applications.

Let’s start with a sample application to create 1000 Contacts in CRM – I am using an on-premise deployment which has a limit of 1000 records for bulk operations. The first thing we need to do is create multiple Entity objects, each of which will be used inside a CreateRequest. The 1000 CreateRequest objects will then be packaged up into a single OrganizationRequestCollection.

Console.WriteLine("Creating 1000 contacts");

OrganizationRequestCollection collection = new OrganizationRequestCollection();

for (int i = 0; i < 1000; i++)
{
    CreateRequest createRequest = new CreateRequest 
    {
        Target = GetEntity()    // this method returns a "contact" Entity
    };

    collection.Add(createRequest);
}

All we need to do now is create and execute the ExecuteMultipleRequest. Note that we have to set the Settings property for the bulk create to work. This property allows us to specify whether the ExecuteMultipleRequest should continue if an error occurs and if responses should be returned.

ExecuteMultipleRequest emRequest = new ExecuteMultipleRequest
{
    Requests = collection,
    Settings = new ExecuteMultipleSettings 
    {
        ContinueOnError = false,
        ReturnResponses = true 
    }
};

Console.WriteLine("Executing request");
ExecuteMultipleResponse emResponse = (ExecuteMultipleResponse)_sdk.Execute(emRequest);
Console.WriteLine("Creation complete");

var results = emResponse.Results;

Run the application and you’ll see the 1000 Contacts created in CRM in no time at all! The ExecuteMultipleResponse object includes a boolean flag to indicate that a failure occurred and also lets us see the results of the bulk operation.

To bulk update or bulk create, simply modify the code and use the UpdateRequest or DeleteRequest objects. In my next post, we will review the performance of the new ExecuteMultipleRequest vs. the single transaction approach. I can’t wait to perform a data migration using this approach!