If you have not read my post Resolving Concurrency conflicts in LINQ then I strongly recommend you to read that. This post is a simple added extension of said post.
After reading resolving concurrency conflict in LINQ you are pretty much aware of resolving mechanism of concurrency conflicts. Now assume a requirement that you need to print or fetch
- Current value of object
- Original value of object on context
- Current data base value.
This is very much possible by
- Enumerating over MemberConflicts of ChangeConflict object.
- Fetching MemberChangeConflict in object of MemberConflict
In child Foreach loop you can fetch values as ,
Catch statement should be modified as below to fetch and print different values.
For reference you can find full source code below,
using System; using System.Linq; using System.Data.Linq; namespace Concurrency { class Program { static void Main(string[] args) { DataClasses1DataContext context = new DataClasses1DataContext(); #region without handling Conflict //Person personToUpdate = (from r in context.Persons // where r.PersonID == 1 // select r).FirstOrDefault(); //personToUpdate.FirstName = "John Papa"; //context.SubmitChanges(); #endregion #region hanlding conflict try { Person personToUpdateConflict = (from r in context.Persons where r.PersonID == 1 select r).FirstOrDefault(); personToUpdateConflict.FirstName = "John"; context.SubmitChanges(ConflictMode.FailOnFirstConflict); } catch (ChangeConflictException c) { foreach (ObjectChangeConflict o in context.ChangeConflicts) { o.Resolve(RefreshMode.KeepChanges); foreach (MemberChangeConflict c1 in o.MemberConflicts) { var currentValue = c1.CurrentValue; var originalValue = c1.OriginalValue; var dataBaseValue = c1.DatabaseValue; Console.WriteLine("Current Value of Object " + c1.CurrentValue); Console.WriteLine("Original value in context " + c1.OriginalValue); Console.WriteLine("Database value " + c1.DatabaseValue); } } context.SubmitChanges(); } #endregion Console.ReadKey(true); } } }
On running application, you should get output as below.
I hope this post was useful. Thanks for reading
Leave a Reply