ExecuteMultiple in Dynamics 365 is used to execute multiple requests, at the same time.
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: -