If you want to prevent duplicates in CRM, you can use duplicate detection rules. This will inform the users, that there is a duplicate, but it’s just an information. The user can click save and the duplicate will be created.
If you use the SDK, you won’t get an information about duplicates automatically. Only if you call the RetrieveDuplicatesRequest, to check for duplicates.
There are two options, which might help:
- You can create a plugin, which checks on each create or update, if there is a duplicate and then throwing an exception.
- You can use alternate keys.
Let’s explain this on an example:
You create accounts, which are having an account number. An account number has to be unique and mustn’t be duplicates. To prevent, that there is an account created with the same account number, we will create an alternate key.
To create an alternate key navigate to settings > customizations > customize the system. Expand the account entity and you will find a section called Keys.
Click on the New-Button, add a Name for the key and select the fields you want to use for the key and click ok.
The key will be created and if everything is correct, the status will switch from pending (during the first check and the creation) to active.
If there was an error during the creation, you can get the error details via the link to the system job.
Now you have a key, which prevents duplicates, but also an additional feature. You got an index on these fields.
This means, if you search for these fields, your results will be delivered faster by the database, as the database can use the automatically created index. You can find the index in your database like on the screenshot below.
If we are creating an entry which violates this key, we are getting an error message:
This message provides all needed information:
- It’s a duplicate
- The alternate key, which is preventing the saving is named in the message.
But there are also some limitation (additional information can be found here):
- Only attributes of the following types can be included in alternate key definitions:
- Decimal Number
- Whole Number
- Single line of text
- When a key is created, the system validates that the key can be supported by the platform, including that the total key size does not violate SQL-based index constraints like 900 bytes per key and 16 columns per key. If the key size doesn’t meet the constraints, an error message will be displayed.
- There can be a maximum of 5 alternate key definitions for an entity in a Dynamics 365 instance.