Tuesday, 31 May 2016

Handling a LINQ ChangeConflict Exception

Multi-user applications using LINQ-to-SQL will commonly come across a ChangeConflictException at run time when a user tried to update a record which if not handled properly can cause a poor user experience as they can lose their changes. This is because it implements the optimistic concurrency approach by default.

There are a couple of ways of handling the ChangeConflictException which occurs when two processes are trying to update the same record in the database at about the same time (i.e. the record has changed in the database since you initially requested it). One way is to just add UpdateCheck = Never on each field in the DataContext which means last change wins - this is a bit crude though and you may actually want to do something more elegant.

Here is one way to handle it in code:

try {
    _db.SubmitChanges(ConflictMode.ContinueOnConflict);
} catch (ChangeConflictException e) {
    _db.ChangeConflicts.ResolveAll(RefreshMode.KeepCurrentValues);
    _db.SubmitChanges(ConflictMode.ContinueOnConflict);
}


Options for ConflictMode are ContinueOnConflict or FailOnFirstConflict
Options for RefreshMode are KeepChanges, KeepCurrentValues, OverwriteCurrentValues
You can then handle it how you want appropriate to the situation

More info: http://weblogs.asp.net/dixin/understanding-linq-to-sql-9-concurrent-conflict

No comments:

Post a Comment