Dataverse Web API Tip #2: Identity Insert


By default, Microsoft Dataverse auto-generates primary key values when data is inserted. Often, this is fine: these GUID key values are not necessarily of interest to users—in fact, users may not even be aware they exist!

However, when external integrations are involved, there are times where it may be advantageous to explicitly set the primary key. That is, instead of Dataverse generating the key’s value for a particular record, you specify what that value should be when you insert the record. In the database world, bypassing an identity column’s auto-generation behavior like this is sometimes known as “identity insert,” as you are inserting the record’s identity value along with the other data that defines it.

For example, suppose you are inserting a record into Dataverse that corresponds with an entity in another system. To link between the two, you could add an “external ID” column to the table in Dataverse and populate it with the corresponding ID from the external system—or if that external ID is a GUID (or can be transformed into a GUID), you could skip creating an extra column and instead simply set the Dataverse record’s primary key value to match the external system’s GUID key!

When using the Dataverse Web API to insert a record, there are a couple ways to specify its primary key:


When creating a record using a POST, include the primary key’s name + value  in the request’s body. The below creates a new contact record, setting its primary key value along with first and last name.

POST {{webApiUrl}}contacts
(include the "Always Include" headers)

  "contactid": "00000000-0000-0000-0000-000000000001",
  "firstname": "Bob", 
  "lastname": "Brown"

If a record with the specified primary key already exists, the request will fail with a 412 Precondition Failed error along the lines of “A  record with matching key values already exists.” (code: 0x80040237).


The primary key can also be set when inserting a record using a PATCH request. Simply specify the desired primary key in the URL and the remaining field values in the request’s body:

PATCH {{webApiUrl}}contacts(00000000-0000-0000-0000-000000000002)
(include the "Always Include" headers)

  "firstname": "Sam", 
  "lastname": "Smith"

PATCH, by default, preforms an upsert (update-or-insert), which means if a record with the specified primary key already exists, it will be updated instead of a new record being inserted or an error being raised complaining about a record with the specified key already existing. Dataverse Web API Tip #3: Upsert talks about this behavior in more detail and explain how to change it when it isn’t desired.

Note: Don’t forget to include the “always include” headers with every request sent to the Web API.

Leave a Reply

Your email address will not be published.