Managing Dataverse N:N relationships between records using the Power Pages Web API can be trickier as there are few samples around and the syntax differs a little bit from handling N:N relationships using the Dataverse Web API.
In this post I will show a quick code sample on how you can handle that, using a sample N:N custom relationship between Contacts and Accounts.
Prerequisites
Associating a Contact with an Account in an N:N relationship
You can use the following JavaScript function to Associate a Contact with an Account in an N:N relationship (replace your_Relationship_Schema_Name by your relationship schema name):
function AssociateRecords(contactId, accountId) {
var parentRecord = {
"@odata.id": `https://${location.host}/_api/accounts(${accountId})`
};
webapi.safeAjax({
type: "POST",
contentType: "application/json",
url: `/_api/contacts(${contactId})/your_Relationship_Schema_Name/$ref`,
data: JSON.stringify(parentRecord),
success: function (data, textStatus, xhr) {
console.log("success");
console.log(xhr.getResponseHeader("entityid"));
},
error: function (xhr, textStatus, errorThrown) {
console.log("error");
console.log(xhr);
}
});
}
This function takes two arguments: contactId and accountId. It creates an object named parentRecord with the property @odata.id that contains a URL pointing to an account record with the given accountId.
Then the function uses the Power Pages Web API to run a POST request with this object into the contact object to create a new reference a for the custom relationship.
Disassociating a Contact with an Account in an N:N relationship
You can use the following JavaScript function to Disassociate a Contact from an Account in an N:N relationship (replace your_Relationship_Schema_Name by your relationship schema name):
function DisassociateRecords(contactId, accountId) {
webapi.safeAjax({
type: "DELETE",
contentType: "application/json",
url: `/_api/contacts(${contactId})/your_Relationship_Schema_Name(${accountId})/$ref`,
success: function (data, textStatus, xhr) {
console.log("success");
console.log(xhr.getResponseHeader("entityid"));
},
error: function (xhr, textStatus, errorThrown) {
console.log("error");
console.log(xhr);
}
});
}
This function uses the Power Pages Web API to run a DELETE request with the URL pointing to an account record with the given accountid and the related contactid relationship reference.
References
How to: Use Portal Web API – Microsoft Learn
Associate and disassociate tables by using the Web API
The post Creating and removing N:N relationships between Dataverse records using JavaScript and Power Pages Web API appeared first on michelcarlo.