JavaScript and the Dynamics 365 WebAPI for Beginners - Associating Records

Dominic Jarvis, 01 May 2018

An action that needs to be commonly performed in Dynamics 365 is associating and disassociating records. These records may be associated via a 1:N or an N:N relationship, and you may want to either create or remove this association.

Performing this action via the WebAPI is actually remarkably easy.

  • •    Identify the Primary Entity
  • •    Identify the Related Entity
  • •    Identify the relationship name

Once these steps have been completed, the association request is a simple POST request, which is easy to execute.

Associating Records

For the purposes of the examples below, I’ll set the following variables:

  • •    ORG URL: Your organisation’s base url – e.g. https://myorg.crm6.dynamics.com
  • •    API URL: Your organisation’s Web API endpoint – e.g. [ORG URL]/api/data/v9.0

In this instance, we’ll associate two accounts using the following request:

POST [API URL]/accounts(acc10000-0000-0000-0000-000000000000)/new_account_account/$ref

The body of the request will be the following object:

image

Let’s see how that looks in JS. In JS, we need to stringify the body object, and we’ll be executing the request using an XMLHttpRequest. This means that we can execute the request synchronously or asynchronously, although, we’ll generally want to execute code like this async so that we don’t freeze the UI.
We’ll also need to set some headers to let Dynamics 365 know what type of content to expect, what content type to give us, what OData version to use and what the max OData version it should be using are.

image

This will associate the two records in Dynamics 365.

This sort of associate request can be used to associate two entities that are share a 1:N relationship, or a N:N relationship. This makes this a viable way of setting lookups.

Disassociating Records

Removing the association is a very similar operation. The main difference is that when we are deleting the record, we will be using the DELETE HTTP method.

While the spec for the DELETE request does not specifically forbid passing data in the body of the request, this is not something that is generally done.

With this request, we will not be passing anything in the body of the request, so the information for the related entity will instead be encoded into the URL.

image

This will disassociate the two records. This method is very handy, as this method of disassociation must be used when clearing the value in a lookup field using the WebAPI.