2
votes

I am using MS Dynamics CRM SDK with C#. In this I have a WCF service method which creates an entity record. I am using CreateRequest in the method. Client is calling this method with 2 identical requests one after other immediately.

There is a fetch before creating a record. If the record is available we are updating it. However, 2 inserts are happening at the exact time. So 2 records with identical data are getting created in CRM.

Can someone help to prevent concurrency?

2
Are you really stuck with CRM 2013? Starting with CRM 2016 you could use Alternate Keys and Upsert request to solve this. - Filburt

2 Answers

3
votes

You should force the duplicate detection rule & decide what to do. Read more

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;
    }
}
0
votes

As Filburt commented in your question, the preferred approach would be to use an Alternate Key and Upsert requests but unfortunately that's not an option for you if you're working with CRM 2013.

In your scenario, I'd implement a very lightweight cache in the WCF service, probably using the MemoryCache object from the System.Runtime.Caching.dll library (small example). Before executing the query to CRM, you can check if the record exists in the cache and continue with you current processing if it doesn't (remembering to add the record to the cache with a small expiration time for potential concurrent executions) or handle the scenario where the record already exists in the cache (and here you can go from having quite complex checks to detect and prevent potential data loss/unnecessary updates to a simple and stupid Thread.Sleep(1000)).