How to handle concurrency in LINQ
Two Things a Good Concurrency System Should Support
A good concurrency system should at least provide two important features:- It should be able to detect if any concurrency violation has taken place.
- Once concurrency violation has been detected, it should provide various ways of how to handle the concurrency violation.
LINQ Supports Optimistic Concurrency by Default
LINQ entity forms the main heart of LINQ engine. All the data from database is fetched usingdatacontext
and given to LINQ objects. Once the data is fetched in the LINQ
objects, the LINQ objects get disconnected from the database. In other
words, LINQ is a disconnected architecture. Due to disconnected
architecture, the only type of locking we can support is optimistic
locking.Good news!!! LINQ supports optimistic concurrency by default.
Let’s See If Really Optimistic Concurrency Works
Let’s do a small sample test to see whether LINQ really supports optimistic concurrency default. So we will do the following:- We will open a data context, fetch a record and modify the record. We will not be calling
SubmitChanges, in other words we will not be making a final update to physical database. - We will then open a new
DataContextconnection, fetch the same record and update the record physically in the database. - Then we will come back to the same old record to call the physical update using
SubmitChanges. In this way, we will be able to simulate concurrency violation.
We first fetch the record and change the customer name but we have not called the physical database commit yet.
Hide Copy Code
DataContext objContext = new DataContext(strConnectionString);
clsCustomer objCustomer = objContext.GetTable<clsCustomer>().First<clsCustomer>();
objCustomer.CustomerName = "Iwanttochange";
We then call a different method which will change this record by which we can simulate concurrency simulation.
Hide Copy Code
SomeOneChangedData();
The SomeOneChangedData method is a simple code which fetches the same record and changes it.
Hide Copy Code
private void SomeOneChangedData()
{
DataContext objContext = new DataContext(strConnectionString);
clsCustomer objCustomer = objContext.GetTable<clsCustomer>().First<clsCustomer>();
// changing to some random customer name
objCustomer.CustomerName = new Random().NextDouble().ToString();
objContext.SubmitChanges();
}
We then come back to the old DataContext object and try to call the SubmitChanges method. This call will create concurrency violation as SomeOneChangedData method has already changed data.
Hide Copy Code
objContext.SubmitChanges();
If you are in debug mode, you should see ChangeConflictException exception thrown as shown in the below figure:try and catch exception block. You should see something as shown in the below figure.Three Ways of Handling Concurrency Violation in LINQ
When we started this article, we talked about the two important features which every good concurrency system should have. We have already seen the live demonstration of the first feature which showed how LINQ helps to detect concurrency conflicts. Now let’s see how LINQ satisfies the second feature for concurrency which is handling concurrency conflicts.LINQ gives three ways by which we can handle concurrency conflicts. To handle concurrency conflicts, we need to wrap the LINQ to SQL code in a
TRY block and catch the ChangeConflictException. We can then loop through the ChangeConflicts collection to specify how we want the conflict to be resolved.
Hide Copy Code
catch (ChangeConflictException ex)
{
foreach (ObjectChangeConflict objchangeconf in objContext.ChangeConflicts)
{
objchangeconf.Resolve(RefreshMode.OverwriteCurrentValues);
}
}
There are 3 ways provided by LINQ system to handle concurrency conflicts:KeepCurrentValues: When this option is specified and concurrency conflicts happen, LINQ keeps calling the LINQ entity object values as it is and does not push the new values from the database into the LINQ object.OverwriteCurrentValues: When this option is specified, the current LINQ object data is replaced with the database values.KeepChanges: This is the most weird option, but can be helpful in some cases. When we talk about classes, it can have many properties. So properties which are changed are kept as they is but the properties which are not changed are fetched from the database and replaced.
RefereshMode to specify which options we need as shown in the below code snippet.Fine Tuning Concurrency at Field Level
One of the best options provided by LINQ concurrency system is control of concurrency behavior at field level. There are three options we can specify using theUpdateCheck attribute:Never: Do not use this field while checking concurrency conflicts.Always: This option specifies that always use this field to check concurrency conflicts.WhenChanged: Only when the member value has changed, use this field to detect concurrency conflicts.
UpdateCheck attribute to control property / field level concurrency options as specified above.
Hide Copy Code
[Column(DbType = "nvarchar(50)",UpdateCheck=UpdateCheck.Never)]
public string CustomerCode
{
set
{
_CustomerCode = value;
}
get
{
return _CustomerCode;
}
}
Error Reporting Options During Concurrency Conflicts
LINQ concurrency system lets you specify how you want the conflicts to be reported. LINQ system has given two ways to report conflicts:ContinueOnConflict: This option says to the LINQ engine to continue even if there are conflicts and finally return all conflicts at the end of the process.FailOnFirstConflict: This option says stop as soon as the first conflict occurs and return all the conflicts at that moment. In other words, LINQ engine does not continue ahead with executing the code.
Both these options can be provided as an input in
SubmitChanges method using the ConflictMode enum. Below is the code snippet of how to specify conflict modes:
Hide Copy Code
objContext.SubmitChanges(ConflictMode.ContinueOnConflict);
Comments
Post a Comment