How can you handle concurrency in LINQ to SQL?

When multiple users are updating the same record at the same time, a conflict will occur. To handle this concurrency conflicts, LINQ provides you following three ways.

  1. KeepCurrentValues – This option will remains the LINQ object values as it is and does not push the new values from the database in to the LINQ object.
  2. OverwriteCurrentValues – This option will replace the LINQ object values with the database values.
  3. KeepChanges – In this case changed properties of an object/entity remains as it is but the properties which are not changed are fetched from the database and replaced.

All these options are available in RefereshMode enum which exist in System.Data.Linq namespace.
To handle concurrency conflicts, wrap the code with in a try block and catch the ChangeConflictException by using catch block and iterate through the ChangeConflicts collection to resolve the conflict as shown below:

DataContext db = new DataContext();
try { // TO DO:
	db.SubmitChanges(ConflictMode.ContinueOnConflict);
} catch (ChangeConflictException ex) {
	foreach(ObjectChangeConflict changeconf in db.ChangeConflicts) {
		changeconf.Resolve(RefreshMode.OverwriteCurrentValues);
	}
}

 

Tagged , . Bookmark the permalink.

Leave a Reply