70-561 - Optimistic concurrency in the Entity Framework

Filed under: , , by:

In the previous post I wrote about optimistic concurrency control (OCC) and about the obvious benefits of using one in your application (although there's still a bunch of developers who don't seem to see those benefits). And I also presented an example of an application that uses LINQ to SQL as OR/M and how to implement optimistic concurrency using out of the box concurrency conflict resolutions. But that mechanism is only available when using LINQ to SQL in your application, and since of .NET 4.0 the Entity Framework is recommended data access solution for LINQ to relational scenarios (Update on LINQ to SQL and LINQ to Entities Roadmap), I decided to demonstrate how the same example would look like when using the Entity Framework instead of LINQ to SQL. So below is our Address entity:

And the application code - again I used partial class to implement Save method that catches and handles concurrency conflicts while saving changes by Object Context class.
[Address.cs]

[AdventureWorksLTEntities]

[Program]

When I first compared the mechanism of resolving concurrency conflicts within the Entity Framework and LINQ to SQL, I thought that now it couldn't be simpler. In Entity Framework all you do is to decided whether you want to keep your changes or keep someone else's changes, which you do by selecting an appropriate refresh mode, which by the way are very descriptive and in my opinion less confusing that it took place in LINQ to SQL, as you choose whether ClientWins or StoreWins. Could it be simpler?! One additional remark - To ensure that objects on the client have been updated by data source-side logic, you can call the Refresh method with the StoreWins value after you call SaveChanges. The SaveChanges method operates within a transaction. SaveChanges will roll back that transaction and throw an exception if any of the dirty ObjectStateEntry objects cannot be persisted. I really hope that more developers will grasp the benefits of having in their application a mechanism of resolving concurrency conflicts - especially if they have decided to use the Entity Framework for object-relational mapping in their projects. And as far as the 70-561 exam, I hope if there's a question on optimistic concurrency in the Entity Framework, you will know the correct answer, but what's more important is to know the correct answer when working with real life projects.

0 comments: