Sam's Microsoft Dynamics 365 Blog

Tuesday 10 September 2019

Using ExecuteMultiple and Upsert Request in C#

ExecuteMultiple in Dynamics 365 is used to execute multiple requests, at the same time.  

In Dynamics 365, we can insert or update request in a single request that is called Upsert. 




Now here we are using a scenario for applying ExecuteMultiple and Upsert Request in a single request.

Here I have created a key inside Contact entity with the name  ”sam_myerpid”. I have mapped ”sam_myerpid” with “ContactId”.

Code:

            ///Creating a list
            List<Customer> customers = new List<Customer>();

            customers.Add(new Customer() { id = 1, firstname = "Sam", lastname = "Khan" });
            customers.Add(new Customer() { id = 2, firstname = "Michel", lastname = "Andrew" });
            customers.Add(new Customer() { id = 3, firstname = "Robert", lastname = "Grew" });

            ///Define ExecuteMultipleRequest
            ExecuteMultipleRequest multipleRequest = new ExecuteMultipleRequest()
            {
                Settings = new ExecuteMultipleSettings()
                {
                    ContinueOnError = true,
                    ReturnResponses = true
                },
                Requests = new OrganizationRequestCollection()
            };
            
            foreach (var cust in customers)
            {
                //Define and add value to KeyAttributeCollection
                KeyAttributeCollection keyColl = new KeyAttributeCollection();
                keyColl.Add("sam_myerpid", cust.id.ToString());

                ///Define Entity and pass KeyAttributeCollection
                Entity custEntity = new Entity("contact", keyColl);

                ///Map fields data
                custEntity.Attributes["firstname"] = cust.firstname;
                custEntity.Attributes["lastname"] = cust.lastname;

                ///Define UpsertRequest
                UpsertRequest req = new UpsertRequest()
                {
                    Target = custEntity
                };

                ///Add UpsertRequest to ExecuteMultipleRequest
                multipleRequest.Requests.Add(req);
            }

            ///Execute
            ExecuteMultipleResponse multipleResponse = (ExecuteMultipleResponse)service.Execute(multipleRequest);


Screenshot: -


So now after execute, this request It will insert records and if there are already records with same ”sam_myerpid” then it will update that records.

  Thanks for reading the article. Hope this Article will helpful for you. Cheers!!!

Source: - 


Web Resource vs PCF vs Canvas App - which of the one is used?

While started working on specific Business Requirements related to custom layout, there is a always common question that "where to star...