C# Code

Dynamics 365 CRM Execute messages in a single database transaction

It is a common requirement in business applications to coordinate changes of multiple records in the system so that either all the data changes succeed, or none of them do. In database terms, this is known as executing multiple operations in a single transaction with the ability to roll back all data changes should any one operation fail.


ExecuteTransactionRequest requestToCreateRecords = null;
// Create an ExecuteTransactionRequest object.
                    requestToCreateRecords = new ExecuteTransactionRequest()
                    {
                        // Create an empty organization request collection.
                        Requests = new OrganizationRequestCollection(),
                        ReturnResponses = true
                    };

                    // Create several (local, in memory) entities in a collection. 
                    EntityCollection input = GetCollectionOfEntitiesToCreate();

                    // Add a CreateRequest for each entity to the request collection.
                    foreach (var entity in input.Entities)
                    {
                        CreateRequest createRequest = new CreateRequest { Target = entity };
                        requestToCreateRecords.Requests.Add(createRequest);
                    }

                    // Execute all the requests in the request collection using a single web method call.
                    try
                    {
                        var responseForCreateRecords =
                            (ExecuteTransactionResponse)_serviceProxy.Execute(requestToCreateRecords);

                        int i = 0;
                        // Display the results returned in the responses.
                        foreach (var responseItem in responseForCreateRecords.Responses)
                        {
                            if (responseItem != null)
                                DisplayResponse(requestToCreateRecords.Requests[i], responseItem);
                            i++;
                        }
                    }
                    catch (FaultException ex)
                    {
                        Console.WriteLine("Create request failed for the account{0} and the reason being: {1}",
                            ((ExecuteTransactionFault)(ex.Detail)).FaultedRequestIndex + 1, ex.Detail.Message);
                        throw;
                    }

private EntityCollection GetCollectionOfEntitiesToCreate()
        {
            return new EntityCollection()
            {
                EntityName = Account.EntityLogicalName,
                Entities = {
                    new Account { Name = "ExecuteTransaction Example Account 1" },
                    new Account { Name = "ExecuteTransaction Example Account 2" },
                    new Account { Name = "ExecuteTransaction Example Account 3" },
                    new Account { Name = "ExecuteTransaction Example Account 4" },
                    new Account { Name = "ExecuteTransaction Example Account 5" }
                }
            };
        }

private void DisplayResponse(OrganizationRequest organizationRequest, OrganizationResponse organizationResponse)
        {
            Console.WriteLine("Created " + ((Account)organizationRequest.Parameters["Target"]).Name
                + " with account id as " + organizationResponse.Results["id"].ToString());
            _newAccountIds.Add(new Guid(organizationResponse.Results["id"].ToString()));
        }

key Points –

  1. Should any one of the requests fail and the transaction is rolled back, any data changes completed during the transaction are undone
  2. Set ReturnResponses to true if you want to get back a collection of responses, one for each message request executed, in the Responses collection
  3. Message requests in the Requests collection are executed in order as they appear in the collection, where the element at index 0 is executed first. This same order is preserved in the Responses collection

2 thoughts on “Dynamics 365 CRM Execute messages in a single database transaction

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 )

Twitter picture

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

Facebook photo

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

Connecting to %s