分享一个dapper简单封装

Posted Yuan.Net

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了分享一个dapper简单封装相关的知识,希望对你有一定的参考价值。

using System;
using System.Data.Common;
using System.Linq;
using Dapper;
using mysql.Data.MySqlClient;

  
public class DapperBase<T> where T:class,new() { /// <summary> /// 读连接 /// </summary> /// <returns></returns> public DbConnection GetWriteConnection() { MySqlConnection connection = new MySqlConnection(WebconfigUtils.GetWriteDbconfig()); //NpgsqlConnection connection = new NpgsqlConnection(_sqlconnection); connection.Open(); return connection; } /// <summary> /// 读连接 /// </summary> /// <returns></returns> public DbConnection GetReadConnection() { try { MySqlConnection connection = new MySqlConnection(WebconfigUtils.GetReadDbconfig()); connection.Open(); return connection; } catch (Exception) { return GetWriteConnection(); } } public T ExecuteSql(string sql, object obj) { using (var connection = GetReadConnection()) { var model = connection.Query<T>(sql, obj) .FirstOrDefault(); connection.Close(); return model; } } /// <summary> /// 事务执行sql /// </summary> /// <param name="sql"></param> /// <param name="obj"></param> /// <returns></returns> public int ExecuteTransactionSql(string sql, object obj) { using (var connection = GetWriteConnection()) { var trans = connection.BeginTransaction(); var rows =connection.Execute(sql, obj,trans); if (rows > 0) { trans.Commit(); } else { trans.Rollback(); } connection.Close(); return rows; } } }

 

以上是关于分享一个dapper简单封装的主要内容,如果未能解决你的问题,请参考以下文章

Dapper 封装01-操作符枚举

简单的方法来分享/讨论/协作的代码片段?

Dapper 封装oracle底层访问数据库

Dapper.Extension的基本使用

NetCore Dapper封装

OSS.Core基于Dapper封装(表达式解析+Emit)仓储层的构思及实现