Run multiple requests with one service call using ExecuteMultipleRequest
If you have been developing on for Dynamics CRM for a while, you probably asked yourself this question at least one: why is there not a way to send multiple service requests with a single call to the organization service. It’s finally here. It was introduced with UR12 on CRM 2011 and is of course available for CRM 2013. The request type isExecuteMultipleRequest. It’s really simple to use. Here are the steps and code snippet below:
- Create a collection of entity records you need to action on (create or update or delete)
- Create the ExecuteMultipleRequest object and add the settings:
- ContinueOnError
- ReturnResponse
- Add a request for each entity to the request collection
- Call the IOrganizationService Execute method and passing the ExecuteMultipleRequest object in parameter
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
| public void ExecutePluginOperation(LocalPluginContext obj) { IOrganizationService service = obj.OrganizationService; IExecutionContext context = obj.PluginExecutionContext; Incident incident = (context.InputParameters[ "Target" ] as Entity).ToEntity<Incident>(); EntityCollection entitesToCreate = GetEntitiesToCreate(incident); ExecuteMultipleRequest requestWithResults = new ExecuteMultipleRequest() { // Assign settings that define execution behavior Settings = new ExecuteMultipleSettings() { ContinueOnError = true , ReturnResponses = true }, // Create an empty organization request collection. Requests = new OrganizationRequestCollection() }; // Add a CreateRequest for each entity to the request collection. foreach ( var entity in entitesToCreate.Entities) { if (entity.Id == Guid.Empty) { CreateRequest createRequest = new CreateRequest { Target = entity }; requestWithResults.Requests.Add(createRequest); } else { UpdateRequest createRequest = new UpdateRequest { Target = entity }; requestWithResults.Requests.Add(createRequest); } } // Execute all the requests in the request collection using a single web method call. ExecuteMultipleResponse responseWithResults = (ExecuteMultipleResponse)service.Execute(requestWithResults); } |
Notes:
- You can only make multiple requests that make changes or create entities of different types (e.g. Contacts, Accounts)
- You can make multiple requests of different types (create, updates and delete requests in a single call)
It’s a very nice performance optimization in certain scenarios!