Retrieve, Update and Delete Record Using Alternate Key in Dynamics CRM Web API

By | October 5, 2016

Before Alternate key concept was introduced in Dynamics CRM it used to be the only GUID of the record which was used to retrieve, update or delete any record. Hence we had to get the record GUID first for any retrieve, update or delete operation. But with the introduction of Alternate keys concept this overhead of getting record GUID went away as we got an alternative way to create any field as Alternate Key and use it. Let’s see how we can perform these operations using Web API now with the help of Alternate keys.

Delete operation in Web API using Alternate key:

function DeleteEntityRecord() {
    var functionName = "DeleteEntityRecord";
    try {
        //get Server url
        var serverURL = Xrm.Page.context.getClientUrl();
        
        var xhr = new XMLHttpRequest();
        
        xhr.open("DELETE", serverURL + "/api/data/v8.0/accounts(accountnumber='AFFSE9IK′)')", true);
        xhr.setRequestHeader("Accept", "application/json");
        xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        xhr.setRequestHeader("OData-MaxVersion", "4.0");
        xhr.setRequestHeader("OData-Version", "4.0");
        xhr.onreadystatechange = function () {
            if (this.readyState == 4) {
                xhr.onreadystatechange = null;
                if (this.status == 204) {
                    //show alert
                    Xrm.Utility.alertDialog('Record Deleted Successfully.');
                }
                else {
                    var error = JSON.parse(this.response).error;
                    //show error
                    Xrm.Utility.alertDialog(error.message);
                }
            }
        };
        xhr.send();
    } catch (e) {
        Xrm.Utility.alertDialog(functionName + (e.message || e.description));
    }
}

In above operation “accountnumber” is Alternate key using which we have performed delete operation.

Update operation in Web API using Alternate key:

function UpdateEntityRecord() {
    var functionName = "UpdateEntityRecord";
    try {
        //get Server url
        var serverURL = Xrm.Page.context.getClientUrl();

        var xhr = new XMLHttpRequest();

        xhr.open("PATCH", serverURL + "/api/data/v8.0/contacts(emailaddress1='Adrian@adventure-works.com')", true);
        xhr.setRequestHeader("Accept", "application/json");
        xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        xhr.setRequestHeader("OData-MaxVersion", "4.0");
        xhr.setRequestHeader("OData-Version", "4.0");
        xhr.onreadystatechange = function () {
            if (this.readyState == 4) {
                xhr.onreadystatechange = null;
                if (this.status == 204) {
                    //show alert
                    Xrm.Utility.alertDialog('Record Updated Successfully.');
                }
                else {
                    var error = JSON.parse(this.response).error;
                    //show error
                    Xrm.Utility.alertDialog(error.message);
                }
            }
        };
        var objContact = {};
        objContact.firstname = "Sam";
        objContact.lastname = "Dsouza";


        var body = JSON.stringify(objContact);
        xhr.send(body);
    } catch (e) {
        Xrm.Utility.alertDialog(functionName + (e.message || e.description));
    }
}

In above operation “emailaddress1” is Alternate key using which we have performed update operation.

Retrieve operation in Web API using Alternate key:

function getEntityByAlternateKey() {
    try {
        var clientUrl = Xrm.Page.context.getClientUrl();
        var xhr = new XMLHttpRequest();
        
        xhr.open("GET", encodeURI(clientUrl + "/api/data/v8.0/contacts(mobilephone=’9568565458′)"), true);

        // For Multiple Alternate keys use like this
        //req.open("GET", encodeURI(clientUrl + "/api/data/v8.0/contacts(mobilephone=’9568565458′,emailaddress1=’Adrian@adventure-works.com’)"), true);

        xhr.setRequestHeader("Accept", "application/json");
        xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        xhr.setRequestHeader("OData-MaxVersion", "4.0");
        xhr.setRequestHeader("OData-Version", "4.0");
        xhr.onreadystatechange = function () {
            if (this.readyState == 4) {
                xhr.onreadystatechange = null;
                if (this.status == 200) {
                    var data = JSON.parse(this.response);
                    var dat = data.value;
                    for (var i = 0; i < dat.length; i++) {
                        var contId = dat[i].contactid;
                        Xrm.Utility.alertDialog("Entity Id : " + contId);
                    }
                }
                else {
                    var error = JSON.parse(this.response).error;
                    Xrm.Utility.alertDialog("Error retrieving Entity- " + error.message);
                }
            }
        };

        xhr.send();
    } catch (e) {
        Xrm.Utility.alertDialog("Error in getting Entity by alternate key – " + e.description);
    }
}

In above operation “mobilephone” is Alternate key using which we have performed retrieve operation.

In this way Alternate keys concept can be used for different operations like to retrieve, update, or delete any record.

Coming to CRMUG SUMMIT? Join us at Booth # 742!

Leave a Reply

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