精巧的异步和交易

时间:2017-08-24 11:31:27

标签: c# asynchronous transactions dapper

我正在试图弄清楚如何在事务中正确使用Dapper。但我仍然认为我做错了什么。我发现的所有示例都没有使用异步。

有人可以告诉我该怎么做吗?

class DapperAsyncTransaction
{
    private readonly IDbConnection _dbConnection;
    private IDbTransaction _dbTransaction;

    private IDbConnection Connection => _dbTransaction.Connection;

    /// <summary>
    /// Constructor
    /// </summary>
    /// <param name="dbConnection"></param>     
    public DapperAsyncTransaction(
        IDbConnection dbConnection)
    {
        _dbConnection = dbConnection;
        _dbConnection.Open();
        _dbTransaction = _dbConnection.BeginTransaction();
    }

    public async Task Execute()
    {
        try
        {
            await Connection.ExecuteAsync(
            @"insert into Persons(Name, Surname) values" +
            "(@Name, @Surname)",
            param: new { Name = "John", Surname = "Doe" },
            transaction: _dbTransaction);


            _dbTransaction.Commit();
        }
        catch (Exception)
        {
            _dbTransaction.Rollback();
        }
        finally
        {
            _dbTransaction.Dispose();
            _dbTransaction = _dbConnection.BeginTransaction();
        }
    }
}

1 个答案:

答案 0 :(得分:2)

将数据库访问权限包装在启用了TransactionScopeAsyncFlowOption的事务范围中。

public async Task AddPerson(string name, string surname)
{
   const string sql = "insert into Persons(Name, Surname) values(@Name, @Surname)";  

   using (var tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
   using (var connection = await _connectionProvider.OpenAsync()) //Or however you get the connection
   {
     await connection.ExecuteAsync(sql, new{name, surname});
     tran.Complete();
   }
}