连接类 引用
using System.Data;
using System.Data.SqlClient;
using Microsoft.Extensions.Configuration;
连接类代码
public class DbHelper
{
private static IDbConnection dbConnection = null;
public static IConfiguration Configuration { get; set; }
private static DbHelper uniqueInstance;
private static readonly object locker = new object();
public DbHelper(IConfiguration configuration)
{
Configuration = configuration;
}
/// <summary>
/// 创建数据库连接
/// </summary>
/// <returns></returns>
public static IDbConnection CreateConnection()
{
IDbConnection connection = null;
connection = new SqlConnection(Configuration["Dbconn"]);
return connection;
}
/// <summary>
/// 创建数据库连接对象并打开链接
/// </summary>
/// <returns></returns>
public static IDbConnection OpenCurrentDbConnection()
{
//判断是否连接
if (dbConnection == null)
{
dbConnection = CreateConnection();
}
//判断连接状态
if (dbConnection.State == ConnectionState.Closed)
{
dbConnection.Open();
}
return dbConnection;
}
/// <summary>
/// 获取实例,这里为单例模式,保证只存在一个实例
/// </summary>
/// <returns></returns>
public static DbHelper GetInstance(IConfiguration configuration)
{
// 双重锁定实现单例模式,在外层加个判空条件主要是为了减少加锁、释放锁的不必要的损耗
if (uniqueInstance == null)
{
lock (locker)
{
if (uniqueInstance == null)
{
uniqueInstance = new DbHelper(configuration);
}
}
}
return uniqueInstance;
}
}
操作类 引用
using Dapper;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
操作类代码
public class DbContext
{
private readonly IConfiguration configuration;
public DbContext(IConfiguration configuration)
{
this.configuration = configuration;
}
// 获取开启数据库的连接
private IDbConnection Db
{
get
{
DbHelper.GetInstance(configuration);//创建单一实例
return DbHelper.OpenCurrentDbConnection();//打开连接
}
}
/// <summary>
/// 查询列表
/// </summary>
/// <param name="sql">查询的sql</param>
/// <param name="param">替换参数</param>
/// <returns></returns>
public async Task<List<dynamic>> Query(string sql, object param = null)
{
return Db.Query<dynamic>(sql, param).ToList();
}
/// <summary>
/// 查询列表
/// </summary>
/// <param name="sql">查询的sql</param>
/// <param name="param">替换参数</param>
/// <returns></returns>
public async Task<List<T>> Query<T>(string sql, object param = null)
{
return (await Db.QueryAsync<T>(sql, param)).ToList();
}
/// <summary>
/// 查询第一个数据
/// </summary>
/// <param name="sql"></param>
/// <param name="param"></param>
/// <returns></returns>
public dynamic QueryFirst(string sql, object param)
{
return Db.QueryFirst<dynamic>(sql, param);
}
/// <summary>
/// 查询第一个数据没有返回默认值
/// </summary>
/// <param name="sql"></param>
/// <param name="param"></param>
/// <returns></returns>
public dynamic QueryFirstOrDefault(string sql, object param)
{
return Db.QueryFirstOrDefault<dynamic>(sql, param);
}
/// <summary>
/// 查询单条数据
/// </summary>
/// <param name="sql"></param>
/// <param name="param"></param>
/// <returns></returns>
public dynamic QuerySingle(string sql, object param)
{
return Db.QuerySingle<dynamic>(sql, param);
}
public async Task<T> QuerySingle<T>(string sql, object parame)
{
return await Db.QuerySingleAsync<T>(sql, parame);
}
/// <summary>
/// 查询单条数据没有返回默认值
/// </summary>
/// <param name="sql"></param>
/// <param name="param"></param>
/// <returns></returns>
public dynamic QuerySingleOrDefault(string sql, object param)
{
return Db.QuerySingleOrDefault<dynamic>(sql, param);
}
/// <summary>
/// 增删改
/// </summary>
/// <param name="sql"></param>
/// <param name="param"></param>
/// <returns></returns>
public int Execute(string sql, object param)
{
return Db.Execute(sql, param);
}
public Task<int> ExecuteAsync(string sql, object param)
{
return Db.ExecuteAsync(sql, param);
}
/// <summary>
/// Reader获取数据
/// </summary>
/// <param name="sql"></param>
/// <param name="param"></param>
/// <returns></returns>
public IDataReader ExecuteReader(string sql, object param)
{
return Db.ExecuteReader(sql, param);
}
/// <summary>
/// Scalar获取数据
/// </summary>
/// <param name="sql"></param>
/// <param name="param"></param>
/// <returns></returns>
public object ExecuteScalar(string sql, object param)
{
return Db.ExecuteScalar(sql, param);
}
/// <summary>
/// Scalar获取数据
/// </summary>
/// <param name="sql"></param>
/// <param name="param"></param>
/// <returns></returns>
public dynamic ExecuteScalarForT(string sql, object param)
{
return Db.ExecuteScalar<dynamic>(sql, param);
}
/// <summary>
/// Scalar获取数据
/// </summary>
/// <param name="sql"></param>
/// <param name="param"></param>
/// <returns></returns>
public dynamic ExecuteScalarAsync<T>(string sql, object param)
{
return Db.ExecuteScalarAsync<T>(sql, param);
}
/// <summary>
/// 带参数的存储过程
/// </summary>
/// <param name="sql"></param>
/// <param name="param"></param>
/// <returns></returns>
public List<dynamic> ExecutePro(string proc, object param)
{
List<dynamic> list = Db.Query<dynamic>(proc,
param,
null,
true,
null,
CommandType.StoredProcedure).ToList();
return list;
}
/// <summary>
/// 事务1 - 全SQL
/// </summary>
/// <param name="sqlarr">salarr</param>
/// <returns></returns>
public int ExecuteTransaction(string[] sqlarr)
{
using (var transaction = Db.BeginTransaction())
{
try
{
int result = 0;
foreach (var sql in sqlarr)
{
result += Db.Execute(sql, null, transaction);
}
transaction.Commit();
return result;
}
catch (Exception)
{
transaction.Rollback();
return 0;
}
}
}
/// <summary>
/// 事务2 - 声明参数
/// </summary>
/// <param name="dic">dic.add(sql,param)</param>
/// <returns></returns>
public async Task<int> ExecuteTransaction(Dictionary<string, object> dic)
{
using (var transaction = Db.BeginTransaction())
{
try
{
int result = 0;
foreach (var sql in dic)
{
result += await Db.ExecuteAsync(sql.Key, sql.Value, transaction);
}
transaction.Commit();
return result;
}
catch (Exception e)
{
transaction.Rollback();
return 0;
}
}
}
/// <summary>
///
/// </summary>
/// <typeparam name="TIn"></typeparam>
/// <param name="model"></param>
/// <param name="tableName"></param>
/// <param name="hasAuto"></param>
/// <returns></returns>
public async Task<bool> InsertAsync<TIn>(TIn model, string tableName = "", bool hasAuto = false)
{
if (string.IsNullOrEmpty(tableName))
tableName = model.GetType().Name;
var sql = GetInserSql<TIn>(tableName, hasAuto);
long row = await Db.ExecuteAsync(sql, model);
return row > 0 ? true : false;
}
/// <summary>
/// 执行插入脚本,并返回自动生成的ID
/// </summary>
/// <typeparam name="TType"></typeparam>
/// <param name="tableName"></param>
/// <param name="haveAuto"></param>
/// <returns></returns>
private static string GetInserSql<TType>(string tableName, bool haveAuto)
{
// todo 未来针对类型,添加语句缓存
var properties = typeof(TType).GetProperties();
var sqlCols = new StringBuilder("INSERT INTO ");
sqlCols.Append(tableName).Append(" (");
var sqlValues = new StringBuilder(" VALUES (");
var isStart = false;
foreach (var propertyInfo in properties)
{
if (isStart)
{
sqlCols.Append(",");
sqlValues.Append(",");
}
else
isStart = true;
sqlCols.Append(propertyInfo.Name);
sqlValues.Append("@").Append(propertyInfo.Name);
}
sqlCols.Append(")");
sqlValues.Append(")");
sqlCols.Append(sqlValues);
//if (haveAuto)
// sqlCols.Append(";SELECT CAST(SCOPE_IDENTITY() AS BIGINT) AS [Id];");
return sqlCols.ToString();
}
/// <summary>
/// 根据对象实体生成对应的更新脚本
/// </summary>
/// <returns></returns>
public async Task<bool> UpdateAsync<TIn>(Expression<Func<TIn, object>> update, Expression<Func<TIn, bool>> where, object mo = null, string tableName = "")
{
if (string.IsNullOrEmpty(tableName))
{
tableName = typeof(TIn).Name;
}
var visitor = new SqlExpressionVisitor();
var updateSql = GetVisitExpressSql(visitor, update, SqlVistorType.Update);
var whereSql = GetVisitExpressSql(visitor, where, SqlVistorType.Where);
var sql = string.Concat("UPDATE ", tableName, " SET ", updateSql, whereSql);
var paras = GetExcuteParas(mo, visitor);
var row = await Db.ExecuteAsync(sql, paras);
return row > 0 ? true : false;
}
/// <summary>
/// 处理where条件表达式,如果表达式为空,默认使用Id
/// </summary>
/// <param name="visitor"></param>
/// <param name="exp"></param>
/// <param name="visType"></param>
private static string GetVisitExpressSql(SqlExpressionVisitor visitor, Expression exp, SqlVistorType visType)
{
if (visType == SqlVistorType.Update)
{
var updateFlag = new SqlVistorFlag(SqlVistorType.Update);
visitor.Visit(exp, updateFlag);
return updateFlag.Sql;
}
var whereFlag = new SqlVistorFlag(SqlVistorType.Where);
visitor.Visit(exp, whereFlag);
var sql = string.Concat(" WHERE ", whereFlag.Sql);
return sql;
}
/// <summary>
/// 获取常量与属性列表
/// </summary>
/// <param name="mo"></param>
/// <param name="visitor"></param>
/// <returns></returns>
private static object GetExcuteParas(object mo, SqlExpressionVisitor visitor)
{
if (!visitor.Parameters.Any())
{
return mo;
}
var paras = new DynamicParameters(visitor.Parameters);
if (mo == null || !visitor.Properties.Any())
{
return paras;
}
paras.AddDynamicParams(mo);
return paras;
}