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.

Generate Your Own New Leads Within Microsoft Dynamics 365 CRM

Contact us for a demo to know more about how Maplytics can help you to generate new leads from within Microsoft Dynamics 365 CRM.

Maplytics is a 5-star rated, preferred business app on the Microsoft AppSource that is Certified for Microsoft Dynamics 365 (CfMD) and comes with powerful features like Appointment Planning, Sales Routing, Territory Management, Heat Maps, Geo-analytical Dashboards and more that empower organizations to add more value to their CRM data, improve sales & service processes, and achieve high ROI.

Get your free trial from our Website or Microsoft AppSource!

‘If data is the new oil, location intelligence is ??”

2 thoughts on “Retrieve, Update and Delete Record Using Alternate Key in Dynamics CRM Web API

  1. Hiren

    I want t to update address where addresstype=1 and ContactID = GUID. how to make such request?

    1. HIREN MODI

      Sorry I want it like AddressType=1 and RelatedContact.alternatekey=”abc”

Comments are closed.