Search code examples
transactionsdynamics-crmmicrosoft-dynamics

Create and update same or different entity record in single ExecuteTransactionRequest or ExecuteMultipleRequest


I want to Create and Update OR Update and Delete records on single or multiple entities in single transaction so that if any co-related transaction gets failed other should be rolled back.

I have tried to search over the net but didn't have luck on this. Is there any possible way we can achieve this?


Solution

  • After a little bit more trials and error I was able to solve this issue. The solution which I'm providing here may not be recommended to all as it I have created GUID in the code. So there might be a performance issue as we creating GUID on the code rather than auto-create in DB side. But yes, this solution worked for me.

                OrganizationRequest req1 = new OrganizationRequest();
                req1.RequestName = "Create";
                Guid newAccountId = Guid.NewGuid();
                var account = new Account()
                {
                    Name = "Acme, Inc.",
                    Id = newAccountId
                };
                req1.Parameters.Add("Target", account);
    
                // Create second account
                OrganizationRequest req2 = new OrganizationRequest();
                account.Name = "Updated name of Acme, Inc.";
                req2.RequestName = "Update";
                req2.Parameters.Add("Target", account);
    
                // Using Execute Multiple 
                ExecuteTransactionRequest multipleRequest = new ExecuteTransactionRequest();
                multipleRequest.Requests = new OrganizationRequestCollection();
                multipleRequest.Requests.Add(req1);
                multipleRequest.Requests.Add(req2);
    
                var responseForRecords = (ExecuteTransactionResponse)_serviceProxy.Execute(multipleRequest);