How to: Resolve Concurrency Conflicts by Retaining Database Values (LINQ to SQL)
To reconcile differences between expected and actual database values before you try to resubmit your changes, you can use OverwriteCurrentValues to retain the values found in the database. The current values in the object model are then overwritten. For more information, see Optimistic Concurrency Overview (LINQ to SQL).
Note
In all cases, the record on the client is first refreshed by retrieving the updated data from the database. This action makes sure that the next update try will not fail on the same concurrency checks.
Example
In this scenario, a ChangeConflictException exception is thrown when User1 tries to submit changes, because User2 has in the meantime changed the Assistant and Department columns. The following table shows the situation.
|
Manager |
Assistant |
Department |
---|---|---|---|
Original database state when queried by User1 and User2. |
Alfreds |
Maria |
Sales |
User1 prepares to submit these changes. |
Alfred |
|
Marketing |
User2 has already submitted these changes. |
|
Mary |
Service |
User1 decides to resolve this conflict by having the newer database values overwrite the current values in the object model.
When User1 resolves the conflict by using OverwriteCurrentValues, the result in the database is as follows in the table:
|
Manager |
Assistant |
Department |
---|---|---|---|
New state after conflict resolution. |
Alfreds (original) |
Mary (from User2) |
Service (from User2) |
The following example code shows how to overwrite current values in the object model with the database values. (No inspection or custom handling of individual member conflicts occurs.)
Dim db As New Northwnd("...")
Try
db.SubmitChanges(ConflictMode.ContinueOnConflict)
Catch ex As ChangeConflictException
Console.WriteLine(ex.Message)
For Each occ As ObjectChangeConflict In db.ChangeConflicts
' All database values overwrite current values.
occ.Resolve(Data.Linq.RefreshMode.OverwriteCurrentValues)
Next
End Try
Northwnd db = new Northwnd("...");
try
{
db.SubmitChanges(ConflictMode.ContinueOnConflict);
}
catch (ChangeConflictException e)
{
Console.WriteLine(e.Message);
foreach (ObjectChangeConflict occ in db.ChangeConflicts)
{
// All database values overwrite current values.
occ.Resolve(RefreshMode.OverwriteCurrentValues);
}
}