CRM SDK – Using Detect Duplicates Settings in Code

In CRM 2011, if you’ve set up a bunch of Duplicate Detection rules, you may want to use these same rules from a plugin or just any general application that utilised the CRM Sdk.

To do this, make sure the duplicate detection settings have been published (see screenshot below):

Then, in code, you can use these duplicate detection settings implicitly by passing in an entity which you’ve not get saved to a method like the following:

/// <summary>
/// Checks for duplicate Guid
/// </summary>
/// <param name="account"></param>
/// <returns>First duplicate account id, if any duplicates found, and Guid.Empty if not</returns>
public Guid DuplicateExists(Account account)
{
    RetrieveDuplicatesRequest request = new RetrieveDuplicatesRequest();
    request.BusinessEntity = account;
    request.MatchingEntityName = Account.EntityLogicalName;
    request.PagingInfo = new PagingInfo();
    request.PagingInfo.PageNumber = 1;
    request.PagingInfo.Count = 1;
 
    RetrieveDuplicatesResponse response = (RetrieveDuplicatesResponse)ServiceProxy.Execute(request);
    return response.DuplicateCollection.Entities.Count > 0 ? response.DuplicateCollection.Entities[0].Id : Guid.Empty;
}

You’ll notice that if you switch off the duplicate detection rule in CRM then this code will not find the duplicate, and if you switch it back on then the duplicate will be detected again. Likewise if you change the definition of the duplicate. This is great if you want to ensure that applications and users are conforming to the same set of duplicate detection rules.

Leave a Reply