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>
UPDATE Order SET OrderID = "New Order 2" WHERE OrderID = 2
Order 1: This is order 1 Order 2: This is order 2 Order 3: This is order 3 UPDATE [dbo].[Order] SET [Introduction] = @p2 WHERE ([OrderID] = @p0) AND ([record_version] = @p1) SELECT [t1].[record_version] FROM [dbo].[Order] AS [t1] WHERE ((@@ROWCOUNT) > 0) AND ([t1].[OrderID] = @p3) -- @p0: Input Int (Size = 0; Prec = 0; Scale = 0) [1] -- @p1: Input Timestamp (Size = 8; Prec = 0; Scale = 0) [SqlBinary(8)] -- @p2: Input NVarChar (Size = 26; Prec = 0; Scale = 0) [Order 1 modified.] -- @p3: Input Int (Size = 0; Prec = 0; Scale = 0) [1] -- Context: SqlProvider(Sql2005) Model: AttributedMetaModel Build: 3.5.21022.8 UPDATE [dbo].[Order] SET [Introduction] = @p2 WHERE ([OrderID] = @p0) AND ([record_version] = @p1) SELECT [t1].[record_version] FROM [dbo].[Order] AS [t1] WHERE ((@@ROWCOUNT) > 0) AND ([t1].[OrderID] = @p3) -- @p0: Input Int (Size = 0; Prec = 0; Scale = 0) [2] -- @p1: Input Timestamp (Size = 8; Prec = 0; Scale = 0) [SqlBinary(8)] -- @p2: Input NVarChar (Size = 26; Prec = 0; Scale = 0) [Order 2 modified.] -- @p3: Input Int (Size = 0; Prec = 0; Scale = 0) [2] -- Context: SqlProvider(Sql2005) Model: AttributedMetaModel Build: 3.5.21022.8 ---------- 1 of 2 updates failed. ---------- Order 1: This is order 1 Order 2: This is order 2 Order 3: This is order 3
也就是说,第一次更新被回滚了。这自然是事务的作用。在调用(默认的) SubmitChanges方法时,Linq to Sql会把所有的更新放在同一个事务中,因此它们“共同进退”。但是由于业务需求不同,有时候我们不希望某条记录的冲突导致了所有更新失败。自然, Linq to Sql也提供了这个方面的控制。在下一篇文章中,我们就来看一下Linq to Sql中与乐观并发控制有关的事务问题,以及出现并发冲突之后的解决方式。拼吾爱
1
延伸阅读
文章来源于领测软件测试网 https://www.ltesting.net/