ASP.NET Core中使用Dapper
⒈添加 NuGet 包
Install-Package Dapper
⒉封装数据库类型
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks; namespace DapperDemo.Data
{
/// <summary>
/// 数据库类型
/// </summary>
public enum DbType
{
Access,
SqlServer,
Oracle,
MySql,
SqlLite
}
}
⒊封装数据库连接仓库
using Microsoft.Extensions.Configuration;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Threading.Tasks; namespace DapperDemo.Data
{
public class DbConnectionFactory
{
/// <summary>
/// 数据库连接字符串缓存
/// </summary>
private static ConcurrentDictionary<string, string> connStrDict = new ConcurrentDictionary<string, string>();
private static IConfiguration Configuration { get; }
private static string GetConnString(string dbKey)
{
string connString = string.Empty;
if (connStrDict.Keys.Contains(dbKey))
{
connString = connStrDict[dbKey];
}
else
{
connString = Configuration[$"ConnectionStrings:{dbKey}"];
connStrDict.TryAdd(dbKey, connString);
}
return connString;
} public static IDbConnection GetConnection(string dbKey, DbType dbType = DbType.SqlServer)
{
IDbConnection connObj = null;
switch (dbType)
{
case DbType.SqlServer:
connObj = new SqlConnection(GetConnString(dbKey));
break;
case DbType.MySql:
connObj = new MySqlConnection(GetConnString(dbKey));
break;
case DbType.Access:
//connObj = new OleDbConnection(GetConnString(dbKey));
break;
case DbType.SqlLite:
break;
case DbType.Oracle:
break;
} if (connObj.State != ConnectionState.Open)
{
connObj.Open();
} return connObj;
} /// <summary>
/// 获取数据连接
/// </summary>
/// <param name="connectionString"></param>
/// <param name="dbType"></param>
/// <returns></returns>
public static IDbConnection GetConnectionByConnString(string connString, DbType dbType = DbType.SqlServer)
{
IDbConnection connObj = null;
switch (dbType)
{
case DbType.SqlServer:
connObj = new SqlConnection(connString);
break;
case DbType.MySql:
connObj = new MySqlConnection(connString);
break;
case DbType.Access:
//connObj = new OleDbConnection(connString);
break;
case DbType.SqlLite:
break;
case DbType.Oracle:
break;
} if (connObj.State != ConnectionState.Open)
{
connObj.Open();
} return connObj;
}
}
}
⒋封装数据库常见方法
using Dapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Threading.Tasks; namespace DapperDemo.Data
{
public class DbRepository
{
private IDbConnection _connection { get; set; }
public string dbConnKey { get; set; }
public DbType dbType { get; set; } public DbRepository(string dbConnKey, DbType dbType = DbType.SqlServer)
{
this.dbConnKey = dbConnKey;
this.dbType = dbType;
} public DbRepository()
{ } public void Init(string dbConnKey, DbType dbType = DbType.SqlServer)
{
this.dbConnKey = dbConnKey;
this.dbType = dbType;
} #region 属性 /// <summary>
/// 获取数据库连接
/// </summary>
public IDbConnection Connection
{
get
{
if (_connection == null)
{
_connection = DbConnectionFactory.GetConnection(dbConnKey, dbType);
}
return _connection;
}
} /// <summary>
/// 事务对象
/// </summary>
public IDbTransaction dbTransaction { get; set; } #endregion #region 事务提交 /// <summary>
/// 事务开始
/// </summary>
/// <returns></returns>
public DbRepository BeginTrans()
{
dbTransaction = Connection.BeginTransaction();
return this;
} /// <summary>
/// 提交当前操作的结果
/// </summary>
public int Commit()
{
try
{
if (dbTransaction != null)
{
dbTransaction.Commit();
this.Close();
}
return ;
}
catch (Exception ex)
{
if (ex.InnerException != null && ex.InnerException.InnerException is SqlException)
{
SqlException sqlEx = ex.InnerException.InnerException as SqlException;
}
throw;
}
finally
{
if (dbTransaction == null)
{
this.Close();
}
}
} /// <summary>
/// 把当前操作回滚成未提交状态
/// </summary>
public void Rollback()
{
this.dbTransaction.Rollback();
this.dbTransaction.Dispose();
this.Close();
} /// <summary>
/// 关闭连接 内存回收
/// </summary>
public void Close()
{
IDbConnection dbConnection = dbTransaction.Connection;
if (dbConnection != null && dbConnection.State != ConnectionState.Closed)
{
dbConnection.Close();
} } #endregion #region 实例方法 #region 查询 /// <summary>
/// 查询
/// </summary>
/// <typeparam name="T">返回类型</typeparam>
/// <param name="sql">sql语句</param>
/// <param name="dbConnKey">数据库连接</param>
/// <param name="param">sql查询参数</param>
/// <param name="commandTimeout">超时时间</param>
/// <param name="commandType">命令类型</param>
/// <returns></returns>
public T QueryFirst<T>(string sql, object param = null, bool buffered = true, int? commandTimeout = default(int?), CommandType? commandType = default(CommandType?))
{
if (dbTransaction == null)
{
using (var dbConn = Connection)
{
return dbConn.QueryFirstOrDefault<T>(sql, param, null, commandTimeout, commandType);
}
}
else
{
return dbTransaction.Connection.QueryFirstOrDefault<T>(sql, param, dbTransaction, commandTimeout, commandType);
} } /// <summary>
/// 查询(异步版本)
/// </summary>
/// <typeparam name="T">返回类型</typeparam>
/// <param name="sql">sql语句</param>
/// <param name="dbConnKey">数据库连接</param>
/// <param name="param">sql查询参数</param>
/// <param name="commandTimeout">超时时间</param>
/// <param name="commandType">命令类型</param>
/// <returns></returns>
public async Task<T> QueryFirstAsync<T>(string sql, object param = null, bool buffered = true, int? commandTimeout = default(int?), CommandType? commandType = default(CommandType?))
{
if (dbTransaction == null)
{
using (var dbConn = Connection)
{
return await dbConn.QueryFirstOrDefaultAsync<T>(sql, param, null, commandTimeout, commandType);
}
}
else
{
return await dbTransaction.Connection.QueryFirstOrDefaultAsync<T>(sql, param, dbTransaction, commandTimeout, commandType);
} } /// <summary>
/// 查询
/// </summary>
/// <typeparam name="T">返回类型</typeparam>
/// <param name="sql">sql语句</param>
/// <param name="dbConnKey">数据库连接</param>
/// <param name="param">sql查询参数</param>
/// <param name="buffered">是否缓冲</param>
/// <param name="commandTimeout">超时时间</param>
/// <param name="commandType">命令类型</param>
/// <returns></returns>
public IEnumerable<T> Query<T>(string sql, object param = null, bool buffered = true, int? commandTimeout = default(int?), CommandType? commandType = default(CommandType?))
{
if (dbTransaction == null)
{
using (var dbConn = Connection)
{
return dbConn.Query<T>(sql, param, null, buffered, commandTimeout, commandType);
}
}
else
{
return dbTransaction.Connection.Query<T>(sql, param, dbTransaction, buffered, commandTimeout, commandType);
} } /// <summary>
/// 查询(异步版本)
/// </summary>
/// <typeparam name="T">返回类型</typeparam>
/// <param name="sql">sql语句</param>
/// <param name="dbConnKey">数据库连接</param>
/// <param name="param">sql查询参数</param>
/// <param name="buffered">是否缓冲</param>
/// <param name="commandTimeout">超时时间</param>
/// <param name="commandType">命令类型</param>
/// <returns></returns>
public async Task<IEnumerable<T>> QueryAsync<T>(string sql, object param = null, bool buffered = true, int? commandTimeout = default(int?), CommandType? commandType = default(CommandType?))
{
if (dbTransaction == null)
{
using (var dbConn = Connection)
{
return await dbConn.QueryAsync<T>(sql, param, null, commandTimeout, commandType);
}
}
else
{
return await dbTransaction.Connection.QueryAsync<T>(sql, param, dbTransaction, commandTimeout, commandType);
} } /// <summary>
/// 查询返回 IDataReader
/// </summary>
/// <param name="sql">sql语句</param>
/// <param name="dbConnKey">数据库连接</param>
/// <param name="param">sql查询参数</param>
/// <param name="commandTimeout">超时时间</param>
/// <param name="commandType">命令类型</param>
/// <returns></returns>
public IDataReader ExecuteReader(string sql, object param = null, int? commandTimeout = default(int?), CommandType? commandType = default(CommandType?))
{
if (dbTransaction == null)
{
using (var dbConn = Connection)
{
return dbConn.ExecuteReader(sql, param, null, commandTimeout, commandType);
}
}
else
{
return dbTransaction.Connection.ExecuteReader(sql, param, dbTransaction, commandTimeout, commandType);
}
} /// <summary>
/// 查询单个返回值
/// </summary>
/// <typeparam name="T">返回类型</typeparam>
/// <param name="sql">sql语句</param>
/// <param name="dbConnKey">数据库连接</param>
/// <param name="param">sql查询参数</param>
/// <param name="commandTimeout">超时时间</param>
/// <param name="commandType">命令类型</param>
/// <returns></returns>
public T ExecuteScalar<T>(string sql, object param = null, int? commandTimeout = default(int?), CommandType? commandType = default(CommandType?))
{
if (dbTransaction == null)
{
using (var dbConn = Connection)
{
return dbConn.ExecuteScalar<T>(sql, param, null, commandTimeout, commandType);
}
}
else
{
return dbTransaction.Connection.ExecuteScalar<T>(sql, param, dbTransaction, commandTimeout, commandType);
} }
#endregion /// <summary>
/// 执行增删改sql
/// </summary>
/// <param name="sql">sql</param>
/// <param name="dbkey">数据库连接</param>
/// <param name="param">sql查询参数</param>
/// <param name="commandTimeout">超时时间</param>
/// <param name="commandType">命令类型</param>
/// <returns></returns>
public int ExecuteSql(string sql, object param = null, int? commandTimeout = default(int?), CommandType? commandType = default(CommandType?))
{
if (dbTransaction == null)
{
using (var dbConn = Connection)
{
return dbConn.Execute(sql, param, null, commandTimeout, commandType);
}
}
else
{
return dbTransaction.Connection.Execute(sql, param, dbTransaction);
}
} /// <summary>
/// 执行增删改sql(异步版本)
/// </summary>
/// <param name="sql">sql</param>
/// <param name="dbkey">数据库连接</param>
/// <param name="param">sql查询参数</param>
/// <param name="commandTimeout">超时时间</param>
/// <param name="commandType">命令类型</param>
/// <returns></returns>
public async Task<int> ExecuteSqlAsync(string sql, object param = null, int? commandTimeout = default(int?), CommandType? commandType = default(CommandType?))
{
if (dbTransaction == null)
{
using (var dbConn = Connection)
{
return await dbConn.ExecuteAsync(sql, param, null, commandTimeout, commandType);
}
}
else
{
await dbTransaction.Connection.ExecuteAsync(sql, param, dbTransaction);
return ;
}
} #endregion #region 静态方法 #region 查询
/// <summary>
/// 查询
/// </summary>
/// <typeparam name="T">返回类型</typeparam>
/// <param name="sql">sql语句</param>
/// <param name="dbConnKey">数据库连接</param>
/// <param name="param">sql查询参数</param>
/// <param name="commandTimeout">超时时间</param>
/// <param name="commandType">命令类型</param>
/// <returns></returns>
public static T QueryFirst<T>(string sql, string dbConnKey, object param = null, DbType dbType = DbType.SqlServer, bool buffered = true, int? commandTimeout = default(int?), CommandType? commandType = default(CommandType?))
{
using (var dbConn = DbConnectionFactory.GetConnection(dbConnKey, dbType))
{
return dbConn.QueryFirstOrDefault<T>(sql, param, null, commandTimeout, commandType);
}
} /// <summary>
/// 查询(异步版本)
/// </summary>
/// <typeparam name="T">返回类型</typeparam>
/// <param name="sql">sql语句</param>
/// <param name="dbConnKey">数据库连接</param>
/// <param name="param">sql查询参数</param>
/// <param name="commandTimeout">超时时间</param>
/// <param name="commandType">命令类型</param>
/// <returns></returns>
public static async Task<T> QueryFirstAsync<T>(string sql, string dbConnKey, object param = null, DbType dbType = DbType.SqlServer, bool buffered = true, int? commandTimeout = default(int?), CommandType? commandType = default(CommandType?))
{
using (var dbConn = DbConnectionFactory.GetConnection(dbConnKey, dbType))
{
return await dbConn.QueryFirstOrDefaultAsync<T>(sql, param, null, commandTimeout, commandType);
}
} /// <summary>
/// 查询
/// </summary>
/// <typeparam name="T">返回类型</typeparam>
/// <param name="sql">sql语句</param>
/// <param name="dbConnKey">数据库连接</param>
/// <param name="param">sql查询参数</param>
/// <param name="buffered">是否缓冲</param>
/// <param name="commandTimeout">超时时间</param>
/// <param name="commandType">命令类型</param>
/// <returns></returns>
public static IEnumerable<T> Query<T>(string sql, string dbConnKey, object param = null, DbType dbType = DbType.SqlServer, bool buffered = true, int? commandTimeout = default(int?), CommandType? commandType = default(CommandType?))
{
using (var dbConn = DbConnectionFactory.GetConnection(dbConnKey, dbType))
{
return dbConn.Query<T>(sql, param, null, buffered, commandTimeout, commandType);
}
} /// <summary>
/// 查询(异步版本)
/// </summary>
/// <typeparam name="T">返回类型</typeparam>
/// <param name="sql">sql语句</param>
/// <param name="dbConnKey">数据库连接</param>
/// <param name="param">sql查询参数</param>
/// <param name="buffered">是否缓冲</param>
/// <param name="commandTimeout">超时时间</param>
/// <param name="commandType">命令类型</param>
/// <returns></returns>
public static async Task<IEnumerable<T>> QueryAsync<T>(string sql, string dbConnKey, object param = null, DbType dbType = DbType.SqlServer, bool buffered = true, int? commandTimeout = default(int?), CommandType? commandType = default(CommandType?))
{
using (var dbConn = DbConnectionFactory.GetConnection(dbConnKey, dbType))
{
return await dbConn.QueryAsync<T>(sql, param, null, commandTimeout, commandType);
}
} /// <summary>
/// 查询返回 IDataReader
/// </summary>
/// <param name="sql">sql语句</param>
/// <param name="dbConnKey">数据库连接</param>
/// <param name="param">sql查询参数</param>
/// <param name="commandTimeout">超时时间</param>
/// <param name="commandType">命令类型</param>
/// <returns></returns>
public static IDataReader ExecuteReader(string sql, string dbConnKey, object param = null, DbType dbType = DbType.SqlServer, int? commandTimeout = default(int?), CommandType? commandType = default(CommandType?))
{
using (var dbConn = DbConnectionFactory.GetConnection(dbConnKey, dbType))
{
return dbConn.ExecuteReader(sql, param, null, commandTimeout, commandType);
}
} /// <summary>
/// 查询单个返回值
/// </summary>
/// <typeparam name="T">返回类型</typeparam>
/// <param name="sql">sql语句</param>
/// <param name="dbConnKey">数据库连接</param>
/// <param name="param">sql查询参数</param>
/// <param name="commandTimeout">超时时间</param>
/// <param name="commandType">命令类型</param>
/// <returns></returns>
public static T ExecuteScalar<T>(string sql, string dbConnKey, object param = null, DbType dbType = DbType.SqlServer, int? commandTimeout = default(int?), CommandType? commandType = default(CommandType?))
{
using (var dbConn = DbConnectionFactory.GetConnection(dbConnKey, dbType))
{
return dbConn.ExecuteScalar<T>(sql, param, null, commandTimeout, commandType);
}
} #endregion #region 增删改 /// <summary>
/// 执行增删改sql
/// </summary>
/// <param name="sql">sql</param>
/// <param name="dbkey">数据库连接</param>
/// <param name="param">sql查询参数</param>
/// <param name="commandTimeout">超时时间</param>
/// <param name="commandType">命令类型</param>
/// <returns></returns>
public static int Execute(string sql, string dbkey, object param = null, DbType dbType = DbType.SqlServer, int? commandTimeout = default(int?), CommandType? commandType = default(CommandType?))
{
using (var dbConn = DbConnectionFactory.GetConnection(dbkey, dbType))
{
return dbConn.Execute(sql, param, null, commandTimeout, commandType);
}
} /// <summary>
/// 执行增删改sql(异步版本)
/// </summary>
/// <param name="sql">sql</param>
/// <param name="dbkey">数据库连接</param>
/// <param name="param">sql查询参数</param>
/// <param name="commandTimeout">超时时间</param>
/// <param name="commandType">命令类型</param>
/// <returns></returns>
public static async Task<int> ExecuteAsync(string sql, string dbkey, object param = null, DbType dbType = DbType.SqlServer, int? commandTimeout = default(int?), CommandType? commandType = default(CommandType?))
{
using (var dbConn = DbConnectionFactory.GetConnection(dbkey, dbType))
{
return await dbConn.ExecuteAsync(sql, param, null, commandTimeout, commandType);
}
} /// <summary>
/// 执行 DynamicQuery.GetInsertQuery* 方法生成的Sql 返回标识值
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="sql"></param>
/// <param name="dbKey"></param>
/// <param name="param"></param>
/// <param name="commandTimeout"></param>
/// <param name="commandType"></param>
/// <returns></returns>
public static T ExecuteInsertSql<T>(string sql, string dbKey, object param = null, DbType dbType = DbType.SqlServer, int? commandTimeout = default(int?), CommandType? commandType = default(CommandType?))
{
using (var dbConn = DbConnectionFactory.GetConnection(dbKey, dbType))
{
return dbConn.QueryFirstOrDefault<T>(sql, param, null, commandTimeout, commandType);
}
} #endregion #endregion }
}
ASP.NET Core中使用Dapper的更多相关文章
- .NET Core中使用Dapper操作Oracle存储过程最佳实践
为什么说是最佳实践呢?因为在实际开发中踩坑了,而且发现网上大多数文章给出的解决方法都不能很好地解决问题.尤其是在获取类型为OracleDbType.RefCursor,输出为:ParameterDir ...
- NET Core中使用Dapper操作Oracle存储过程
.NET Core中使用Dapper操作Oracle存储过程最佳实践 为什么说是最佳实践呢?因为在实际开发中踩坑了,而且发现网上大多数文章给出的解决方法都不能很好地解决问题.尤其是在获取类型为Or ...
- 如何在ASP.NET Core中编写高效的控制器
通过遵循最佳实践,可以编写更好的控制器.所谓的"瘦"控制器(指代码更少.职责更少的控制器)更容易阅读和维护.而且,一旦你的控制器很瘦,可能就不需要对它们进行太多测试了.相反,你可 ...
- ASP.NET Core 中的那些认证中间件及一些重要知识点
前言 在读这篇文章之间,建议先看一下我的 ASP.NET Core 之 Identity 入门系列(一,二,三)奠定一下基础. 有关于 Authentication 的知识太广,所以本篇介绍几个在 A ...
- Asp.net Core中使用Session
前言 2017年就这么悄无声息的开始了,2017年对我来说又是特别重要的一年. 元旦放假在家写了个Asp.net Core验证码登录, 做demo的过程中遇到两个小问题,第一是在Asp.net Cor ...
- 在ASP.NET Core中使用百度在线编辑器UEditor
在ASP.NET Core中使用百度在线编辑器UEditor 0x00 起因 最近需要一个在线编辑器,之前听人说过百度的UEditor不错,去官网下了一个.不过服务端只有ASP.NET版的,如果是为了 ...
- ASP.NET Core中的依赖注入(1):控制反转(IoC)
ASP.NET Core在启动以及后续针对每个请求的处理过程中的各个环节都需要相应的组件提供相应的服务,为了方便对这些组件进行定制,ASP.NET通过定义接口的方式对它们进行了"标准化&qu ...
- ASP.NET Core中的依赖注入(2):依赖注入(DI)
IoC主要体现了这样一种设计思想:通过将一组通用流程的控制从应用转移到框架之中以实现对流程的复用,同时采用"好莱坞原则"是应用程序以被动的方式实现对流程的定制.我们可以采用若干设计 ...
- ASP.NET Core中的依赖注入(3): 服务的注册与提供
在采用了依赖注入的应用中,我们总是直接利用DI容器直接获取所需的服务实例,换句话说,DI容器起到了一个服务提供者的角色,它能够根据我们提供的服务描述信息提供一个可用的服务对象.ASP.NET Core ...
随机推荐
- elasticsearch利用head插件
restful接口使用方法 RESTful接口URL的格式: http://localhost:9200///[] 其中index.type是必须提供的. id是可选的,不提供es会自动生成. ind ...
- linux向文件中添加数据,数据被追加到了上一行的行尾
当我们在windows上新建了文件,并且要上传到linux上时,一定要在文件后加上空格,否则就会出现标题上讲的,数据被追加到了上一行的行尾,而不是新起一行,但是如果是在linux上新建的文件,则没有这 ...
- SQLServer通过链接服务器调用Oracle 存储过程
语法: declare @输出参数 数据类型; exec(' exec 存储过程(?, ?)', 输入参数, @输出参数 out) at 链接服务器名 参考文章: SQL2008 链接Oracle 调 ...
- linux内核中的subsys_initcall是干什么的?
注意:使用的内核源码版本为5.1.3 1. subsys_initcall长什么样子? 它其实是个宏定义,定义如下: #define subsys_initcall(fn) __define_ ...
- redis 概述及部署 安装php和python客户端
概述 Redis是一个基于key-value键值对的持久化数据库存储系统.redis支持的数据存储类型比memcached更丰富,包括strings(字符串),lists(列表),sets(集合)和s ...
- .netcore centos配置systemctl自动启动
systemd分两种服务系统和用户服务 对应存储位路径为系统(/usr/lib/systemd/system).用户(/etc/systemd/user/) [Unit] Description=ap ...
- MOCK服务小结
前言: 说到mock,大家会想到单测中的mock,测试同学会想到httpmock服务等. mock的作用:程序运行过程中,设定过滤规则及返回值,来满足固定的数据解析,解决不容易构造或者获取的数据对象. ...
- Jmeter联机负载时报错: connection refused to host localhost,nested exception is:java.net ConnectException:Connection refused:connect
Jmeter联机负载时报错: connection refused to host localhost,nested exception is:java.net ConnectException:C ...
- iOS 隐藏导航栏后,UITableView向下偏移状态栏高度
if (@available(iOS 11.0, *)) { self.mainTableView.contentInsetAdjustmentBehavior = UIScrollViewConte ...
- Java并发包concurrent——ConcurrentHashMap
转: Java并发包concurrent——ConcurrentHashMap 2018年07月19日 20:43:23 Bill_Xiang_ 阅读数 16390更多 所属专栏: Java Conc ...