Using Alternate keys is an easy way to stop doing pre and post checks for whether you can insert data into Dynamics.
Before you had to do a check behind the scenes for whether an “Id” existed and if not go and insert it.
Now using the “Upsert” pattern in Dynamics, you can accomplish this task in one method call using an alternate key.
At’s it’s most simplest implementation, I created a custom entity and a field (wholenumber) that I then declared as my alternate key.
Then I wrote the following code to insert the following record into my system. You can see in the entity description that I have highlighted the alternate key along with the id value itself. This is a great implementation because even if you have different physical key schemas in Dynamics (i.e., an old system) you can give them a consistent naming scheme across the board, simplifying your code.
//This is our upsert method with an alternate key Entity super = new Entity("btrv_superent", "btrv_altid", 5); super["btrv_name"] = "Gregger the Beggar"; super["btrv_randotext"] = "random data"; super["btrv_randotext2"] = "random data 5000"; super["btrv_randotext3"] = "more random data"; UpsertRequest req = new UpsertRequest(); req.Target = super; UpsertResponse resp = (UpsertResponse)svc.Execute(req);
From my code, you can also access the newly Inserted or Updated Crm Guid id and whether the record was Inserted or Updated in the last operation.
This is a great implementation that can simply data migration and synchronization functions when working with data across different boundaries with different meanings in those target environments.