标签:closed 多次 started pen tab action start type pre
ef中,savechanges() 默认使用事务.
using (var context = new BookStore()) { context.Database.Log = Console.WriteLine; Author author1 = new Author() { Name = "Mark" }; Author author2 = new Author() { Name = "John" }; context.Authors.Add(author1); context.SaveChanges(); context.Authors.Add(author2); context.SaveChanges(); }
可以看到一个事务把两个insert包起来
Opened connection at 10/29/2018 9:18:26 AM +00:00 Started transaction at 10/29/2018 9:18:26 AM +00:00 INSERT [dbo].[Authors]([Name]) VALUES (@0) SELECT [AuthorId] FROM [dbo].[Authors] WHERE @@ROWCOUNT > 0 AND [AuthorId] = scope_identity() -- @0: ‘Mark‘ (Type = String, Size = -1) -- Executing at 10/29/2018 9:18:26 AM +00:00 -- Completed in 3 ms with result: SqlDataReader Committed transaction at 10/29/2018 9:18:26 AM +00:00 Closed connection at 10/29/2018 9:18:26 AM +00:00 Opened connection at 10/29/2018 9:18:26 AM +00:00 Started transaction at 10/29/2018 9:18:26 AM +00:00 INSERT [dbo].[Authors]([Name]) VALUES (@0) SELECT [AuthorId] FROM [dbo].[Authors] WHERE @@ROWCOUNT > 0 AND [AuthorId] = scope_identity() -- @0: ‘John‘ (Type = String, Size = -1) -- Executing at 10/29/2018 9:18:26 AM +00:00 -- Completed in 1 ms with result: SqlDataReader Committed transaction at 10/29/2018 9:18:26 AM +00:00 Closed connection at 10/29/2018 9:18:26 AM +00:00
如果你想在一个事务中多次执行savechanges 你应该这样写
using (var context = new BookStore()) { context.Database.Log = Console.WriteLine; using (DbContextTransaction transaction = context.Database.BeginTransaction()) { try { Author author1 = new Author() { Name = "Mark" }; Author author2 = new Author() { Name = "John" }; context.Authors.Add(author1); context.SaveChanges(); context.Authors.Add(author2); context.SaveChanges(); transaction.Commit(); } catch (Exception ex) { transaction.Rollback(); } } }
Opened connection at 10/29/2018 9:21:20 AM +00:00 Started transaction at 10/29/2018 9:21:20 AM +00:00 INSERT [dbo].[Authors]([Name]) VALUES (@0) SELECT [AuthorId] FROM [dbo].[Authors] WHERE @@ROWCOUNT > 0 AND [AuthorId] = scope_identity() -- @0: ‘Mark‘ (Type = String, Size = -1) -- Executing at 10/29/2018 9:21:20 AM +00:00 -- Completed in 3 ms with result: SqlDataReader INSERT [dbo].[Authors]([Name]) VALUES (@0) SELECT [AuthorId] FROM [dbo].[Authors] WHERE @@ROWCOUNT > 0 AND [AuthorId] = scope_identity() -- @0: ‘John‘ (Type = String, Size = -1) -- Executing at 10/29/2018 9:21:20 AM +00:00 -- Completed in 0 ms with result: SqlDataReader Committed transaction at 10/29/2018 9:21:20 AM +00:00 Closed connection at 10/29/2018 9:21:20 AM +00:00
标签:closed 多次 started pen tab action start type pre
原文地址:https://www.cnblogs.com/nocanstillbb/p/11495042.html