轻量级ORM框架Dapper应用支持操作函数和事物
时间:2022-06-12 09:36:11|栏目:.NET代码|点击: 次
dapper除了支持基础的CURD、存储过程以外,还支持操作函数和事物。
dapper操作函数的代码如下:
using Dapper; using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DapperDemo { public static class OperFunction { /// <summary> /// Dapper滴调用函数 /// </summary> public static void ExecuteFunction() { // 连接字符串 string strCon = ConfigurationManager.ConnectionStrings["DbConnection"].ConnectionString; // connection对象 IDbConnection dbConnection = new SqlConnection(strCon); // 定义参数 DynamicParameters paras = new DynamicParameters(); paras.Add("@num1", 34); paras.Add("@num2", 456); // 返回值 paras.Add("@sum", 0, DbType.Int32, ParameterDirection.ReturnValue); string functionName = "fun_test"; // 执行 int count = dbConnection.Execute(functionName, paras, null, null, CommandType.StoredProcedure); // 获取输出参数的值 int sum = paras.Get<int>("@sum"); Console.WriteLine("sum:" + sum);//输出390 } } }
dapper支持事物的代码如下:
using Dapper; using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DapperDemo { public static class OperTransaction { /// <summary> /// Dapper支持事物 /// </summary> public static void ExecuteTransaction() { // 连接字符串 string strCon = ConfigurationManager.ConnectionStrings["DbConnection"].ConnectionString; // connection对象 IDbConnection dbConnection = new SqlConnection(strCon); string strSQL = "DELETE FROM Student WHERE StudentID=@StudentID"; DynamicParameters paras = new DynamicParameters(); paras.Add("@StudentID", 3); // 在BeginTransaction之前要打开连接,否则报错:无效操作,连接已关闭 dbConnection.Open(); // 开启事物 IDbTransaction transaction = dbConnection.BeginTransaction(); try { dbConnection.Execute(strSQL, paras, transaction: transaction); // 提交事务 transaction.Commit(); } catch (Exception ex) { // 回滚事物 transaction.Rollback(); } } } }
Dapper除了支持Transaction以外,还支持Transactionscope:
public static void ExecuteTransactionScope() { using (var transactionscope = new TransactionScope(TransactionScopeOption.Required)) { // 连接字符串 string strCon = ConfigurationManager.ConnectionStrings["DbConnection"].ConnectionString; // connection对象 IDbConnection dbConnection = new SqlConnection(strCon); string strSQL = "DELETE FROM Student WHERE StudentID=@StudentID"; DynamicParameters paras = new DynamicParameters(); paras.Add("@StudentID", 6); dbConnection.Open(); try { dbConnection.Execute(strSQL, paras); transactionscope.Complete(); } catch (Exception ex) { // 不提交事务默认自动回滚 Console.WriteLine(ex.Message); } } }