分享一个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; } } }

 

文章来自:http://www.cnblogs.com/fangyuan303687320/p/5513813.html
© 2021 jiaocheng.bubufx.com  联系我们
ICP备案:鲁ICP备09046678号-3