Friday, December 9, 2011

Avoid duplicates when creating / updating records using the CRM SDK

When you enable duplicate detection and publish your duplicate detection rules, you will notice that when you try to create a duplicate in the CRM web application (or through Outlook client) you will get a pop-up indicating that you are trying to create a duplicate record. However, if the create/update request is sent via the web services to CRM (using the SDK) then by default, the duplicate record will be created without any warning.

The trick is that if you want to avoid creating duplicates when calling the CRM web services, you need to provide an optional parameter in the request which specifies that the server should check for duplicates before creating your record (by default the server will bypass duplicate detection). You must use a CreateRequest or UpdateRequest and provide the SuppressDuplicateDetection as “false”. Here is a sample for which my code will prevent creating duplicate accounts (note that I have already published a duplicate detection rule for accounts with the same name):

 

Account a = new Account();
a.Name = "My account";

CreateRequest req = new CreateRequest();
req.Parameters.Add("SuppressDuplicateDetection", false);
req.Target = a;
try
{
    service.Execute(req);
}
catch (FaultException<OrganizationServiceFault> ex)
{
    if (ex.Detail.ErrorCode == -2147220685)
    {
        // Account with name "My account" already exists
    }
    else
    {
        throw;
    }
}

4 comments:

  1. Is it possible to add the SuppressDuplicateDetection parameter in a plugin so that its always set to false for all requests?

    Any thoughts much appreciated.

    John

    ReplyDelete
  2. Yes, you can use the same sample code above within plugins. However, you must set the parameter for each Create/Update Request, there is now way to set it to false globally always.

    ReplyDelete
  3. Nice post! Where can I get more info about the error codes returned by the api (like -2147220685 in this case)?
    Thanks!

    ReplyDelete
  4. Hi! We are using MS CRM 2011 and have a customised Inventory Booking form. On clicking the "SAVE" button a booking record gets written in the underlying inventory booking form table. However while testing we have observed that if two users at the same time book the same inventory item and Click "SAVE at the same instant then two records are written in the Inventory Booking Form Table which is not what we want. Any particular inventory should be booked under one and only one user. How do I circumvent this problem. I was told " Duplicate enablement in MS CRM is an option but the duplicate Matching key gets generated every 5 minutes so this too may not solve the problem on hand. Kindly help!

    ReplyDelete