Retrieval of Many-to-Many (N:N) Relationship Records using Web API in Dynamics 365

By | April 10, 2019

Introduction

In this blog we will learn to retrieve Dynamic CRM entity records in respect of Many to Many relationships between two Dynamic CRM entities (OOB/Custom).

So let’s take a look at the following example:

In the below screeshot, there is one Many-to-Many relationship present between Account and Territory Entity of Dynamic CRM.

Web API in Dynamics 365

One Territory entity subgrid is added to the Account entity form.

Web API in Dynamics 365

So, now we need to retrieve Account entity records which are associated with the three territories shown in the above screenshot (i.e California, Nevada, New York). For this, we need to first prepare the fetchXml query for retrieving the Account entity records.

<fetch version=”1.0″ output-format=”xml-platform” mapping=”logical” distinct=”true”>

<entity name=”account”>

<attribute name=”name” />

<order attribute=”name” descending=”false” />

<link-entity name=”new_account_territory_entity_name” from=”accountid” to=”accountid”    visible=”false” intersect=”true”>

<link-entity name=”territory” from=”territoryid” to=”territoryid” alias=”ab”>

<filter type=”and”>

<filter type=”or”>

<condition attribute=”name” operator=”eq” value=”Nevada” />

<condition attribute=”name” operator=”eq” value=”New York” />

</filter>

</filter>

<attribute name=”name” />

<attribute name=”territoryid” />

</link-entity>

</link-entity>

</entity>

</fetch>

 

Note:

new_account_territory_entity_name: It is defined as IntersectEntityName which you can get from N:N relationship record as shown in the screenshot below.

accountid:  It is defined as Entity1IntersectAttribute attribute which you can get from N:N relationship record.

Web API in Dynamics 365

Now run this fetchXml query using Web API.

//create AJAX request

Maplytics_jQ.ajax({

type: “GET”,

contentType: “application/json; charset=utf-8”,

datatype: “json”,

//async: false,

url: this.getWebAPIPath() + entitySetName + “?fetchXml=” + fetchXml,

beforeSend: function (xhr) {

//Specifying this header ensures that the results will be returned as JSON.

xhr.setRequestHeader(“Accept”, “application/json”);

xhr.setRequestHeader(“Content-Type”, “application/json; odata.metadata=minimal”);

xhr.setRequestHeader(“OData-MaxVersion”, “4.0”);

xhr.setRequestHeader(“OData-Version”, “4.0”);

xhr.setRequestHeader(“Prefer”, “odata.include-annotations=*”);

},

success: function (data, textStatus, xhr) {

 

},

error: function (xhr, textStatus, errorThrown) {

retrieveUsingFetchError(Inogic.Maplytics.ApiLib.errorHandler(xhr));

}

});

Conclusion

The above query will help to retrieve Account records which are associated with three territories records (i.e Nevada, New York, California).

Easily-Export-Dynamics-365-Reports-in-PDF-Word-or-Excel

 

Leave a Reply

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