Bulk Insert and Bulk Update in MS CRM

Create a record and update a record is very crucial in CRM. There may be a scenario where we need to create or update no. of records at a time. Rather than doing that individually we can do that as Bulk with the below process.

Ex: Consider I need to create 10 records at a time for a requirement. So we need to add those 10 entities to EntityCollection..

EntityCollection entitiesToCreate = new EntityCollection(); //Assume that i have added 10 entites to this collection

var multipleInsertRequest = new ExecuteMultipleRequest()
{
    // Assign settings that define execution behavior: continue on error, return responses.
    Settings = new ExecuteMultipleSettings()
    {
        ContinueOnError = false,
        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 entitiesToCreate.Entities)
{
    CreateRequest createRequest = new CreateRequest { Target = entity };
    multipleInsertRequest.Requests.Add(createRequest);
}

ExecuteMultipleResponse multipleInsertResponse = (ExecuteMultipleResponse)service.Execute(multipleInsertRequest );


Similarly to update multiple records:

EntityCollection entitiesToUpdate = new EntityCollection(); //Assume that i have added 10 entites to this collection

var multipleUpdateRequest = new ExecuteMultipleRequest()
                {
                    // Assign settings that define execution behavior: continue on error, return responses.
                    Settings = new ExecuteMultipleSettings()
                    {
                        ContinueOnError = false,
                        ReturnResponses = true
                    },
                    // Create an empty organization request collection.
                    Requests = new OrganizationRequestCollection()
                };

                // Add a UpdateRequest for each entity to the request collection.
                foreach (var entity in entitiesToUpdate.Entities)
                {
                    UpdateRequest updateRequest = new UpdateRequest { Target = entity };
                    multipleUpdateRequest.Requests.Add(updateRequest);
                }

                // Execute all the requests in the request collection using a single web method call.
                ExecuteMultipleResponse multipleResponse = (ExecuteMultipleResponse)service.Execute(multipleUpdateRequest);


No comments:

Post a Comment

Featured Post

Improving MS CRM Performance

Performance on MS CRM is always a crucial thing and we may follow different ways to achieve the performance thing. Below is the one more a...