Do optimistic concurrency works?

 Posted by ArticlesMaint on 9/30/2009 | Category: LINQ Interview questions | Views: 3175


For that let us do a small sample test to show LINQ really support 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 final update to physical database.

• We will then open a new ‘DataContext’ connection, 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.

So below goes the code.

We first fetch the record and change the customer name but we have not called the physical database commit yet.
 

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.
 

SomeOneChangedData();


 


The ‘SomeOneChangedData’ method is a simple code which fetches the same record and changes it.
 

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.
 

objContext.SubmitChanges();


 


If you are in debug mode you should see ‘ChangeConflictException’ exception thrown as shown in the below figure.
 



If you want to really see the exception you can run the code without try and catch exception block. You should see something as shown in the below figure.



Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Login to post response