Dapper中對事務的處理也非常簡單,如下代碼所示:
1 private void DapperTransaction() 2 { 3 using (IDbConnection con = OpenConnection()) 4 { 5 IDbTransaction tran = con.BeginTransaction(); 6 try 7 { 8 string query = "update T_Role set RoleName='開發主管' where RoleId=4";//更新一條記錄 9 con.Execute(query, null, tran, null, null); 10 //throw new Exception(); 11 query = "delete from T_Role where RoleId=8";//刪除一條記錄 12 con.Execute(query, null, tran, null, null); 13 tran.Commit(); 14 } 15 catch (Exception ex) 16 { 17 tran.Rollback(); 18 } 19 } 20 }