Batch updating fields with crmsvcutil generated code


“I love early bound code because of compile time checking, LINQ query enablement, etc.  I want to batch update a bunch of records, but OrganizationServiceContext.SaveChanges() executes under the hood as one web service call per entity.  How do I batch update?  Also, how do I make sure that only the fields I change are updated?”

The answer is that you basically have to combine your crmsvcutil.exe generated code with ExecuteMultipleResults.  Here’s an example:

var conn = CrmConnection.Parse("USE A VALID connection string using appropriate format documented at");
var ctx = new marcsctest1Context(new OrganizationService(conn));

// NOTE: The query below uses LINQ projection.  The CRM LINQ provider will translate this to a query that only returns ID & Name
var query = 
    from a in ctx.AccountSet
    select new Account
        Id = a.Id,
        Name = a.Name

var executeMultipleRequest = new ExecuteMultipleRequest()
    Settings = new ExecuteMultipleSettings(){
        ContinueOnError = false,
        ReturnResponses = true
    Requests = new OrganizationRequestCollection()

foreach (var account in query)
    account.Name += " - Updated";
    //UpdateObject is required to set the EntityState to Changed because it is readonly through crmsvcutil generated entities

    executeMultipleRequest.Requests.Add(new UpdateRequest()
        Target = account

//Don't forget to check response.IsFaulted and handle appropriately
var response = ctx.Execute(executeMultipleRequest) as ExecuteMultipleResponse;


Comments (1)

  1. Alan says:

    Are the early bound APIs going to be updated to allow batch operations to be expressed more succinctly?

Skip to main content