Thursday, April 24, 2014

How to use ExecuteMultipleRequest with ServiceContext and Linq

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);