Blogs

Concurrency Control – Prevent multiple users from modifying the same record at the same time.

, January 31, 20187251 Views

The Dynamics CRM is used by multiple users. So, the possibility of multiple users trying to update the same record at a time is very high. In such situation, changes made by the latest user will be saved. This results into inconsistent data, when the same fields are updated by the users at the same time.

Thus, the Microsoft Xrm SDK provides concurrency control mechanism, while updating and deleting the record through UpdateRequest & DeleteRequest respectively.

Note:- In order to use the concurrency control mechanism of the Microsoft Xrm SDK, you must import the Microsoft.Xrm.Sdk namespace.(i.e using Microsoft.Xrm.Sdk;)

Below is a code implementing concurrency control mechanism:-

// Retrieve Account Record
Entity accountRecord = _service.Retrieve("account", new Guid("00000000-0000-0000-0000-000000000000"), new ColumnSet(true));
                
// Code to Update the Record
// Initialize new Object to update
   Entity updateRecord = new Entity();
   updateRecord.Id = accountRecord.Id;
   updateRecord.LogicalName = accountRecord.LogicalName;

// Set the RowVersion Property of the Updating record
   updateRecord.RowVersion = accountRecord.RowVersion;

// Update Name
   updateRecord["name"] = "Account Changed";

   UpdateRequest updateReq = new UpdateRequest();

   updateReq.Target = updateRecord;

// Set the Concurrency Behaviour before executing the Update request & match the Row 
// Versions of the record before executing the Request
   updateReq.ConcurrencyBehavior = ConcurrencyBehavior.IfRowVersionMatches;

// Do the update.
   UpdateResponse updateResponse = (UpdateResponse)_service.Execute(updateReq);

Now, if the name of the record is changed in CRM at the same time by a different user, before UpdateRequest is executed. Then, _service.Execute() will give an Exception: ‘The version of the existing record doesn’t match the RowVersion property provided.’ and it would not be executed successfully.

If you want to forcibly perform the Update operation through code, then, simply change this line as mentioned below:

//Set the Concurrency Behaviour before executing the Update request to Ignore the check and update the record successfully
updateReq.ConcurrencyBehavior = ConcurrencyBehavior.AlwaysOverwrite;

In the same way, concurrency control can be maintained, while deleting the record using DeleteRequest as mentioned below:

// Create Delete Request
DeleteRequest delRequest = new DeleteRequest()
{
  Target = accountRecord.ToEntityReference(),
  ConcurrencyBehavior = ConcurrencyBehavior.IfRowVersionMatches
};

_service.Execute(delRequest);

I Hope this helps you…

Happy CRMing!!


 

Insert data into Many-to-Many relationship in Dynamics CRM very easily & quickly, using the Drag and drop listbox.
http://www.inkeysolutions.com/what-we-do/dynamicscrmaddons/drag-and-drop-listbox