在Linq to Sql中管理并发更新时的冲突(3):使用记录的时间戳进行检测
那么,我们一直说出现了“并发更新冲突”,那么发生冲突后又会出现什么问题呢?我们来看一个略有些复杂的示例:
try { LinqToSqlDemoDataContext dataContext = new LinqToSqlDemoDataContext(); Order order1 = dataContext.Orders.Single(o => o.OrderID == 1); Order order2 = dataContext.Orders.Single(o => o.OrderID == 2); Order order3 = dataContext.Orders.Single(o => o.OrderID == 3); Console.WriteLine("Order 1:" + order1.Introduction); Console.WriteLine("Order 2:" + order2.Introduction); Console.WriteLine("Order 3:" + order3.Introduction); Console.WriteLine(); order1.Introduction = "Order 1 modified."; order2.Introduction = "Order 2 modified."; order3.Introduction = "Order 3 modified."; dataContext.Log = Console.Out; // 在下面的语句上设置一个断点 dataContext.SubmitChanges(); } catch (ChangeConflictException e) { Console.WriteLine("---------- ' + e.Message + ' ----------"); } LinqToSqlDemoDataContext db = new LinqToSqlDemoDataContext(); Order o1 = db.Orders.Single(o => o.OrderID == 1); Order o2 = db.Orders.Single(o => o.OrderID == 2); Order o3 = db.Orders.Single(o => o.OrderID == 3); Console.WriteLine("Order 1: " + o1.Introduction); Console.WriteLine("Order 2:" + o2.Introduction); Console.WriteLine("Order 3:" + o3.Introduction); Console.ReadLine();
假设我们的数据表里有以下三条记录:
OrderID | Name | Introduction | record_version |
1 | Order 1 | This is order 1 | <Binary data> |
2 | Order 2 | This is order 2 | <Binary data> |
3 | Order 3 | This is order 3 | <Binary data> |