With the release of CRM Online Spring 2015 Update, Microsoft delivered the ability to define alternate keys for an entity. Alternate keys can be one or many attributes that are a unique combination of columns to uniquely identify a record instead of using the typical primary key. Alternate keys can be made up from a combination of decimal, integer or string attributes.
Lets dig into how the new alternate keys can work in CRM based on a real-world scenario.
In my example we have an entity for States and our Contact entity has a Lookup to the State entity. The State entity has an attribute called Code where it will store the unique two character abbreviation for the State such as IL for Illinois. There is an integration with another system where Contacts will be passed to Dynamics along with the two character abbreviation for State. Alternate keys work perfectly in this scenario as we can just associate the State record to the Contact record by using the State’s Code instead of needing to query to find it’s GUID.
In order to accomplish this, we first need to go to the customizations for the State entity. Underneath the entity is a new link for Keys.
Click New which will open a dialog and let you pick one or more keys that will make up a unique combination to identify a record. We will select Code as a Key for our State entity.
Now with the SDK when updating a Contact record, in order the set a Lookup value we would need to use the EntityReference object and provide a GUID to a State record but with the latest Spring Update and the latest SDK, we can instead pass in a value for the Code attribute like shown in the snippet below.
Therefore if our integration sends us a Code for the Contact’s State such as “IL”, we can just update our Contact record using the “IL” value and avoid needing to do a query against the State entity to find the GUID for the IL State record.
One last thing to point out about alternate keys is that CRM will put a constraint on the entity to make sure the new alternate keys make up a unique identifier for the entity. If you try creating a record with a duplicate set of alternate keys, you will see an error similar to the one shown below.