Using Upsert In C# Dynamics 365

3 Comments

In this post we will look at how to use Upsert to insert/update a record in Dynamics 365.

Let’s say we have a contact in the system, Bob Smith:

We would like to do an upsert on Bob Smith. To do this, we need to find his record using a key, so the system can decide whether to do the insert or update. To do this, we use Alternate Keys. To set up an Alternate Key, go to the entity in Customizations and click on Keys. Click New:

We will use First Name and Last Name as the Key:

Click OK. They key will be in Pending status:

Wait until it changes to Active. Any issues, click on the Status link. Note if your data contains non-unique values based on your new key, you will need to resolve those:

Now, in Visual Studio, create a console app:

Select Console App:

Add Microsoft.CrmSdk.Xrm.Tooling.CoreAssembly using NuGet:

Let’s write the code to do the upsert. We will add a jobtitle as well to show the update.

The code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Microsoft.Xrm.Tooling.Connector;
using Microsoft.Xrm.Sdk;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Messages;
using System.ServiceModel;

namespace Carl.Dynamics365Upsert
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                var connectionString = @"AuthType = Office365; Url = https://yourorg.crm.dynamics.com/;Username=your@email;Password=yourpassword";
                CrmServiceClient conn = new CrmServiceClient(connectionString);

                IOrganizationService service;
                service = (IOrganizationService)conn.OrganizationWebProxyClient != null ? (IOrganizationService)conn.OrganizationWebProxyClient : (IOrganizationService)conn.OrganizationServiceProxy;

                // Set alternate Key
                KeyAttributeCollection altKey = new KeyAttributeCollection();
                altKey.Add("firstname", "Bob");
                altKey.Add("lastname", "Smith");

                Entity contact = new Entity("contact", altKey);
                contact["firstname"] = "Bob";
                contact["lastname"] = "Smith";
                contact["jobtitle"] = "CEO";

                UpsertRequest request = new UpsertRequest()
                {
                    Target = contact
                };

                try
                {
                    UpsertResponse response = (UpsertResponse)service.Execute(request);
                    if (response.RecordCreated)
                        Console.WriteLine("Record created");
                    else
                        Console.WriteLine("Record updated");
                }

                // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
                catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>)
                {
                    throw;
                }
                Console.ReadLine();

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.ReadLine();
            }
        }
    }
}

Run the code. As Bob Smith already exists, we will see:

With the updated record:

If we delete Bob Smith and run the same code, Bob Smith will be created:

 

 

ABOUT CARL DE SOUZA

Carl de Souza is a developer and architect focusing on Microsoft Dynamics 365, BI, Web, Cloud and Data Science.

carldesouza.comLinkedIn Twitter | YouTube

 

3 Responses to Using Upsert In C# Dynamics 365

  1. This is a good article. Do you have one in which you have two Alternate Keys? The create does well however I’m receiving errors like:

    A record that has the attribute values [MY_ALT_KEY_ATTRIBUTES] already exists. The entity key [MY_ALT_KEY_NAME] requires that this set of attributes contains unique values. Select unique values and try again.

Leave a Reply

Your email address will not be published. Required fields are marked *