2017-08-24 78 views
1

我想弄清楚如何正確使用小巧的事務。但我仍然認爲我做錯了什麼。我發現的所有例子都沒有使用異步。小巧的異步和交易

難道有人會告訴我該怎麼做對嗎?

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(); 
     } 
    } 
} 
+0

解釋爲什麼你認爲這是錯誤的。這個例子是非常沒有意義的,除非涉及到'Persons'觸發器,因爲你只做一個單獨的操作,它已經在它自己的隱式事務中操作了(假設MSSQL) – Crowcoder

回答

1

只是在啓用了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(); 
    } 
}