Tuesday, 7 April 2015

Bulk Record deletion in CRM

You may need to delete record in the bunch of 350 records at a time to delete them rather them deleting one by one. Below is the code which is deleting System Jobs of the bunch of 350.

    List<Guid> lstAsynId = _context.AsyncOperationSet.Where(p => p.OperationType.Value == 10 && p.ErrorCode != null).Select(p => p.Id).ToList<Guid>();

        long Total = 0;

        ExecuteMultipleRequest bulkreq = new ExecuteMultipleRequest()

        {

            Settings = new Microsoft.Xrm.Sdk.ExecuteMultipleSettings()

            {

                ContinueOnError = true,

                ReturnResponses = false

            },

            Requests = new Microsoft.Xrm.Sdk.OrganizationRequestCollection()

        };


        int flag = 0;

        int batchsize = 350; //define the number of records for deletion


        foreach (Guid asyncId in lstAsynId)
        {

            if (flag < batchsize)
            {

                bulkreq.Requests.Add(new DeleteRequest()

                {

                    Target = new Microsoft.Xrm.Sdk.EntityReference(AsyncOperation.EntityLogicalName, asyncId)

                });

                flag++;

            }


            if (flag == batchsize)
            {

                _service.Execute(bulkreq);

                bulkreq.Requests = new Microsoft.Xrm.Sdk.OrganizationRequestCollection();

                flag = 0;

            }

            //service.Delete("activitymimeattachment", Attachment.ID);

        }

        _service.Execute(bulkreq);

    }

No comments:

Post a Comment