10.事务
Posted nocanstillbb
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了10.事务相关的知识,希望对你有一定的参考价值。
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
以上是关于10.事务的主要内容,如果未能解决你的问题,请参考以下文章
95-10-130-启动-TransactionCoordinator