Using Upsert In C# Dynamics 365

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.