码迷,mamicode.com
首页 > 移动开发 > 详细

分享一个dapper简单封装

时间:2016-05-21 01:24:06      阅读:2342      评论:0      收藏:0      [点我收藏+]

标签:

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简单封装

标签:

原文地址:http://www.cnblogs.com/fangyuan303687320/p/5513813.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!