web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Customer experience | Sales, Customer Insights,...
Suggested Answer

Bulk create/update

(0) ShareShare
ReportReport
Posted on by 407

Hi,

I would like to know, Can I use ExecuteMultipleRequest for bulk create/update. I have nearly 250000 records.

How feasible it is to used ExecuteMultipleRequest ?

Regards

Aniket

I have the same question (0)
  • Suggested answer
    ajyendra Profile Picture
    1,738 on at

    Hi,

    i also done bulk update through console application around 3+ lac records.

    provide you a code below it might too long but check it works for you.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using Microsoft.Xrm.Sdk;
    using Microsoft.Xrm.Sdk.Client;
    using System.Net;
    using System.ServiceModel.Description;
    using Microsoft.Xrm.Sdk.Messages;
    using Microsoft.Xrm.Sdk.Query;
    using System.Xml;
    using System.IO;

    namespace ProcessCancel
    {
    class Program
    {
    static void Main(string[] args)
    {
    ClientCredentials credentials = new ClientCredentials();

    credentials.UserName.UserName = "xxxx@yyyy.onmicrosoft.com"; //Username

    credentials.UserName.Password = "abcabcac"; //Password

    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

    Uri serviceUri = new Uri("">xxxxxxxx.api.crm.dynamics.com/.../Organization.svc"); //Organization url

    OrganizationServiceProxy proxy = new OrganizationServiceProxy(serviceUri, null, credentials, null);

    proxy.EnableProxyTypes();

    IOrganizationService service = (IOrganizationService)proxy;
    Console.WriteLine("Connected");
    UpdateInBulk(proxy);

    }

    public static void UpdateInBulk(OrganizationServiceProxy _orgService)
    {
    Int32 pageNumber = 1;
    // Initialize the number of records.
    int fetchCount = 1000;
    // Specify the current paging cookie. For retrieving the first page,
    // pagingCookie should be null.
    string pagingCookie = null;
    string fetchXml = @"<fetch distinct='false' mapping='logical' output-format='xml-platform' version='1.0'>
    <entity name='asyncoperation'>
    <attribute name='asyncoperationid'/>
    <attribute name='name'/>
    <attribute name='regardingobjectid'/>
    <attribute name='operationtype'/>
    <attribute name='statuscode'/>
    <attribute name='ownerid'/>
    <attribute name='startedon'/>
    <attribute name='statecode'/>
    <attribute name='createdon'/>
    <order descending='true' attribute='startedon'/>
    <filter type='and'>
    <condition attribute='createdon' operator='on' value='2019-08-17' />
    <condition attribute='statuscode' value='10' operator='eq'/>
    <condition attribute='operationtype' value='10' operator='eq'/>
    <condition attribute = 'name' value = 'Set field in elevator performance evaluation' operator='eq' />
    </filter>
    </entity>
    </fetch>";
    while (true)
    {
    // Build fetchXml string with the placeholders.
    string xml = CreateXml(fetchXml, pagingCookie, pageNumber, fetchCount);
    // Excute the fetch query and get the xml result.
    RetrieveMultipleRequest fetchRequest1 = new RetrieveMultipleRequest
    {
    Query = new FetchExpression(xml)
    };
    EntityCollection returnCollection = ((RetrieveMultipleResponse)_orgService.Execute(fetchRequest1)).EntityCollection;
    List<Entity> updateCollection = new List<Entity>();
    foreach (var c in returnCollection.Entities)
    {

    var updateEntity = new Entity("asyncoperation");
    updateEntity.Id = c.Id;
    updateEntity["statuscode"] = new OptionSetValue(32); // 32 is for status cancelled
    updateEntity["statecode"] = new OptionSetValue(3);
    try
    {
    updateCollection.Add(updateEntity);
    }
    catch (Exception ex)
    {
    Console.WriteLine("Error1");
    Console.ReadKey();
    }
    }
    BulkUpdateSystemJobRecords(_orgService, updateCollection);
    // Check for morerecords, if it returns 1.
    if (returnCollection.MoreRecords)
    {
    Console.WriteLine("\n****************\nPage number {0}\n****************", pageNumber);
    // Increment the page number to retrieve the next page.
    pageNumber++;
    // Set the paging cookie to the paging cookie returned from current results.
    pagingCookie = returnCollection.PagingCookie;


    }
    else
    {
    // If no more records in the result nodes, exit the loop.
    break;
    }
    }
    }
    public static void BulkUpdateSystemJobRecords(IOrganizationService service, List<Entity> entities)
    {
    // Create an ExecuteMultipleRequest object.
    var multipleRequest = 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 entities)
    {
    UpdateRequest updateRequest = new UpdateRequest { Target = entity };
    multipleRequest.Requests.Add(updateRequest);
    }

    // Execute all the requests in the request collection using a single web method call.
    try
    {
    ExecuteMultipleResponse multipleResponse = (ExecuteMultipleResponse)service.Execute(multipleRequest);
    }
    catch (Exception ex)
    {
    Console.WriteLine("Error");
    Console.ReadKey();
    }

    }


    public static string CreateXml(string xml, string cookie, int page, int count)
    {
    StringReader stringReader = new StringReader(xml);
    XmlTextReader reader = new XmlTextReader(stringReader);

    // Load document
    XmlDocument doc = new XmlDocument();
    doc.Load(reader);

    return CreateXml(doc, cookie, page, count);
    }

    public static string CreateXml(XmlDocument doc, string cookie, int page, int count)
    {
    XmlAttributeCollection attrs = doc.DocumentElement.Attributes;

    if (cookie != null)
    {
    XmlAttribute pagingAttr = doc.CreateAttribute("paging-cookie");
    pagingAttr.Value = cookie;
    attrs.Append(pagingAttr);
    }

    XmlAttribute pageAttr = doc.CreateAttribute("page");
    pageAttr.Value = System.Convert.ToString(page);
    attrs.Append(pageAttr);

    XmlAttribute countAttr = doc.CreateAttribute("count");
    countAttr.Value = System.Convert.ToString(count);
    attrs.Append(countAttr);

    StringBuilder sb = new StringBuilder(1024);
    StringWriter stringWriter = new StringWriter(sb);

    XmlTextWriter writer = new XmlTextWriter(stringWriter);
    doc.WriteTo(writer);
    writer.Close();

    return sb.ToString();
    }
    }
    }

    For log file you can append the log code below link:

    https://docs.microsoft.com/en-us/dotnet/standard/io/how-to-open-and-append-to-a-log-file

    Note: ExecuteMultipleRequest  has limitation it cannot execute more than 1000 record a time . 

    But above code I used paging to continue it until all the matched record is done. Use Carefully.

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > Customer experience | Sales, Customer Insights, CRM

#1
Tom_Gioielli Profile Picture

Tom_Gioielli 70 Super User 2025 Season 2

#2
Gerardo Rentería García Profile Picture

Gerardo Rentería Ga... 43 Most Valuable Professional

#3
Daniyal Khaleel Profile Picture

Daniyal Khaleel 32 Most Valuable Professional

Last 30 days Overall leaderboard

Product updates

Dynamics 365 release plans