dapper支持操作函数和事物
dapper除了支持基础的CURD、存储过程以外,还支持操作函数和事物。
dapper操作函数的代码如下:
1 using Dapper; 2 using System; 3 using System.Collections.Generic; 4 using System.Configuration; 5 using System.Data; 6 using System.Data.SqlClient; 7 using System.Linq; 8 using System.Text; 9 using System.Threading.Tasks; 10 11 namespace DapperDemo 12 { 13 public static class OperFunction 14 { 15 /// <summary> 16 /// Dapper滴调用函数 17 /// </summary> 18 public static void ExecuteFunction() 19 { 20 // 连接字符串 21 string strCon = ConfigurationManager.ConnectionStrings["DbConnection"].ConnectionString; 22 // connection对象 23 IDbConnection dbConnection = new SqlConnection(strCon); 24 // 定义参数 25 DynamicParameters paras = new DynamicParameters(); 26 paras.Add("@num1", 34); 27 paras.Add("@num2", 456); 28 // 返回值 29 paras.Add("@sum", 0, DbType.Int32, ParameterDirection.ReturnValue); 30 string functionName = "fun_test"; 31 // 执行 32 int count = dbConnection.Execute(functionName, paras, null, null, CommandType.StoredProcedure); 33 // 获取输出参数的值 34 int sum = paras.Get<int>("@sum"); 35 Console.WriteLine("sum:" + sum);//输出390 36 } 37 } 38 }
dapper支持事物的代码如下:
1 using Dapper; 2 using System; 3 using System.Collections.Generic; 4 using System.Configuration; 5 using System.Data; 6 using System.Data.SqlClient; 7 using System.Linq; 8 using System.Text; 9 using System.Threading.Tasks; 10 11 namespace DapperDemo 12 { 13 public static class OperTransaction 14 { 15 /// <summary> 16 /// Dapper支持事物 17 /// </summary> 18 public static void ExecuteTransaction() 19 { 20 // 连接字符串 21 string strCon = ConfigurationManager.ConnectionStrings["DbConnection"].ConnectionString; 22 // connection对象 23 IDbConnection dbConnection = new SqlConnection(strCon); 24 string strSQL = "DELETE FROM Student WHERE StudentID=@StudentID"; 25 DynamicParameters paras = new DynamicParameters(); 26 paras.Add("@StudentID", 3); 27 // 在BeginTransaction之前要打开连接,否则报错:无效操作,连接已关闭 28 dbConnection.Open(); 29 // 开启事物 30 IDbTransaction transaction = dbConnection.BeginTransaction(); 31 try 32 { 33 dbConnection.Execute(strSQL, paras, transaction: transaction); 34 // 提交事务 35 transaction.Commit(); 36 } 37 catch (Exception ex) 38 { 39 // 回滚事物 40 transaction.Rollback(); 41 } 42 } 43 } 44 }
Dapper除了支持Transaction以外,还支持Transactionscope:
1 public static void ExecuteTransactionScope() 2 { 3 using (var transactionscope = new TransactionScope(TransactionScopeOption.Required)) 4 { 5 // 连接字符串 6 string strCon = ConfigurationManager.ConnectionStrings["DbConnection"].ConnectionString; 7 // connection对象 8 IDbConnection dbConnection = new SqlConnection(strCon); 9 string strSQL = "DELETE FROM Student WHERE StudentID=@StudentID"; 10 DynamicParameters paras = new DynamicParameters(); 11 paras.Add("@StudentID", 6); 12 dbConnection.Open(); 13 try 14 { 15 dbConnection.Execute(strSQL, paras); 16 transactionscope.Complete(); 17 } 18 catch (Exception ex) 19 { 20 // 不提交事务默认自动回滚 21 Console.WriteLine(ex.Message); 22 } 23 } 24 }