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;


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s