Retrieve Data using Alternate Key in Dynamics 365

Follow my blog for more interesting topics on Dynamics 365, Portals and Power Platform. For training and consulting, write to us at info@xrmforyou.com
Alternate keys have been implemented some time back and by now I think most of the consultants working with Microsoft Dynamics are familiar with the concept of alternate keys.
In case you are new to alternate key, you can follow the below documentation here.
https://docs.microsoft.com/en-us/dynamics365/customer-engagement/developer/define-alternate-keys-entity
Recently I got a request to retrieve using an alternate key. Strangely enough, there are many examples of Update/ Upsert using alternate key but not much with the retrieve using SDK.
Moreover developers coming in new gets confused whenever they try to retrieve using OrganzationService.Retrieve because the method does not have any parameter to take in an alternate key
Well the alternative to that is using the RetrieveRequest. Below is the sample code to retrieve a contact record with alternate key. The alternate key is set up on the Email (emailaddress1) field of the contact entity.

string entName = "contact";
            string alternateKeyfield = "emailaddress1";
            RetrieveRequest retrieveRequest = new RetrieveRequest();
            retrieveRequest.ColumnSet = new ColumnSet(new string[2] { "firstname", "lastname" });
            retrieveRequest.Target = new EntityReference(entName, alternateKeyfield, "test@123.com");
            RetrieveResponse resp = (RetrieveResponse)proxy.Execute(retrieveRequest);
            if(resp.Entity != null)
            {
                Console.WriteLine($"First Name: {resp.Entity.GetAttributeValue<string>("firstname")}");
                Console.WriteLine($"Last Name: {resp.Entity.GetAttributeValue<string>("lastname")}");
             }

Strangely enough the RetrieveRequest is hardly being used. The highlighted one is the line where we are trying to retrieve using Alternate key which is set on emailaddress1 field.
Please note if there is no record with the specified email address here (test@123.com), you will get an error. Your code should have appropriate try catch block to handle the same
Hope this helps next time when you try to retrieve a record using alternate key.
Debajit Dutta
(Dynamics MVP)
For consultation/ corporate training visit www.xrmforyou.com or reach out to us at info@xrmforyou.com


Discover more from Debajit's Power Apps & Dynamics 365 Blog

Subscribe to get the latest posts sent to your email.

2 thoughts on “Retrieve Data using Alternate Key in Dynamics 365”

Comments are closed.

Discover more from Debajit's Power Apps & Dynamics 365 Blog

Subscribe now to keep reading and get access to the full archive.

Continue reading