本文小编为大家详细介绍“怎么用Dapper”,内容详细,步骤清晰,细节处理妥当,希望这篇“怎么用Dapper”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。
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); } }}
读到这里,这篇“怎么用Dapper”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注编程网行业资讯频道。