Retrieve Duplicate Detection Rules Using CRM SDK

In this article you will learn how to retrieve duplicate detection rules using CRM SDK.

Sometimes you may require to retrieve duplicate detection rules using CRM SDK. This post will help you to write code to get duplicate detection rule. Let’s take an example, we want to retrieve all the duplicate detection rules based on the entity name. If you will navigate to Settings-> Data Management -> Duplicate Detection Rules, you will see duplicate detection rules for entities. For example, below is the duplicate rules for contact entity.

  1. using(OrganizationService crmService = new OrganizationService("OrganizationService"))  
  2. {  
  3.     QueryExpression query = new QueryExpression  
  4.     {  
  5.         EntityName = "duplicaterule",  
  6.             ColumnSet = new ColumnSet("name"),  
  7.             Criteria = {  
  8.                 FilterOperator = LogicalOperator.And,  
  9.                     Conditions = {  
  10.                         new ConditionExpression  
  11.                         {  
  12.                             AttributeName = "baseentityname",  
  13.                                 Operator = ConditionOperator.Equal,  
  14.                                 Values = {  
  15.                                     "contact"  
  16.                                 }  
  17.                         },  
  18.                         new ConditionExpression  
  19.                         {  
  20.                             AttributeName = "statecode",  
  21.                                 Operator = ConditionOperator.Equal,  
  22.                                 Values = {  
  23.                                     1  
  24.                                 }  
  25.                         }  
  26.                     }  
  27.             }  
  28.     };  
  29. }  
  30. EntityCollection entityCollection = crmService.RetrieveMultiple(query);  
In the above code we are retrieving only published duplicate rules, so it will fetch two records for us.

After that we can loop through entity collection to get individual duplicate rule if required using the following code:
  1. foreach (Entity duplicaterule in entityCollection.Entities)  
  2. {  
  3.    //processing entitycollection records  
  4. }  
Also in case you need unpublished duplicate rules you can check statecode like the following code snippet:
  1. new ConditionExpression  
  2. {  
  3.    AttributeName="statecode",  
  4.    Operator=ConditionOperator.Equal,  
  5.    Values={0}  
  6. }