交易与小巧的网点

我想在多个表上运行多个插入语句。 我正在使用dapper.net。 我没有看到任何处理与dapper.net交易的方式。

请分享您如何使用dapper.net进行交易的想法。

这里的代码片段:

using System.Transactions; .... using (var transactionScope = new TransactionScope()) { DoYourDapperWork(); transactionScope.Complete(); } 

请注意,您需要添加对System.Transactions程序集的引用,因为它在默认情况下未被引用。

我更喜欢使用更直观的方法,直接从连接中获取事务:

 // This method will get a connection, and open it if it's not yet open. using (var connection = GetOpenConnection()) using (var transaction = connection.BeginTransaction()) { connection.Execute( "INSERT INTO data(Foo, Bar) values (@Foo, @Bar);", listOf5000Items, transaction); transaction.Commit(); } 

你应该可以使用TransactionScope因为Dapper只运行ADO.NET命令。

 using (var scope = new TransactionScope()) { // insert // insert scope.Complete(); } 

丹尼尔的回答对我来说是正常的。 为了完整起见,下面是一个使用事务范围和精简器来演示提交和回滚的代码片段:

 using System.Transactions; // _sqlConnection has been opened elsewhere in preceeding code using (var transactionScope = new TransactionScope()) { try { long result = _sqlConnection.ExecuteScalar<long>(sqlString, new {Param1 = 1, Param2 = "string"}); transactionScope.Complete(); } catch (Exception exception) { // Logger initialized elsewhere in code _logger.Error(exception, $"Error encountered whilst executing SQL: {sqlString}, Message: {exception.Message}") // re-throw to let the caller know throw; } } // This is where Dispose is called 

考虑到你所有的表都在单个数据库中,我不同意在这里的一些答案中提出的TransactionScope解决scheme。 参考这个答案。

  1. TransactionScope通常用于分布式事务; 跨不同数据库的事务可能在不同的系统上。 这需要在操作系统和SQL Server上进行一些configuration,否则这将不起作用。 如果您的所有查询都是针对单个数据库实例的,则不推荐这样做。

  2. connection.BeginTransaction是ADO.NET语法,用于实现事务(在C#,VB.NET等)针对单个数据库。 这不适用于多个数据库。

所以, connection.BeginTransaction()是更好的方法。

即使处理交易的更好的方法是按照这个答案中的解释来实现UnitOfWork。