Monday, May 6, 2013

How to use ExecuteMultipleRequest with ServiceContext and Linq

Most of  CRM2011 developers must have used the service context and linq before. I have also blogged about it in the past in one of my plug-in tutorial. CRM rollup 12 has introduced a new method “ExecuteMultipleRequest”. This method receives a collection of requests (same or different type of requests). The method return the response collection. Here is the link to sample code from Microsoft.

I was playing around this method and came across some code from my favourite CRM expert “David Berry”. I tried to use his code with service context and here is the result. I have hard coded few things in my sample but you can change it as required.

The following code is retrieving all the contacts where parent customer id is C6CB814A-BA75-E011-8720-00155DA5304E and updating their phone number.

var ServiceContext = new OrganizationServiceContext(service);
Guid accountid = new Guid("C6CB814A-BA75-E011-8720-00155DA5304E");

// Create an ExecuteMultipleRequest object.
ExecuteMultipleRequest requestWithResults = new ExecuteMultipleRequest()
    // Assign settings that define execution behavior: continue on error, don't return responses. 
    Settings = new ExecuteMultipleSettings()
        ContinueOnError = false,
        ReturnResponses = false
    // Create an empty organization request collection.
    Requests = new OrganizationRequestCollection()
requestWithResults.Requests.AddRange(from c in ServiceContext.CreateQuery("contact")
                                    where c["parentcustomerid"].Equals(accountid)
                                    select new UpdateRequest()
                                        Target = new Entity("contact")
                                            Id = c.Id,
                                            Attributes = { new KeyValuePair<string,object>("telephone1", "+61402234212") }

// Excute the requests
ExecuteMultipleResponse Response = (ExecuteMultipleResponse)service.Execute(requestWithResults);

If you are using any other entity collection then you can change ServiceContext.CreateQuery("contact") with that.

I have highlighted the following lines
ContinueOnError = false
ReturnResponses = false

These lines are self explanatory. The first line means that continue on error and the second line means that do not return the response. 
Please check the code from Microsoft for complete/detailed explanation.

1 comment: