封装了一些sqlsugar的常用方法 用来动态切换数据库和依赖注入 支持泛型
接口:
/// <summary>
/// 数据库操作
/// </summary>
public interface IDAL_Services
{
/// <summary>
/// 添加数据(实体模式)
/// </summary>
/// <param name="connectionStrings">要连接的数据库</param>
/// <param name="model">插入的数据</param>
/// <returns></returns>
Task<bool> InsertData<TEntity>(string connectionStrings, TEntity model) where TEntity : class, new();
/// <summary>
/// 添加数据集(实体模式)
/// </summary>
/// <param name="connectionStrings">要连接的数据库</param>
/// <param name="model">插入的数据</param>
/// <returns></returns>
Task<bool> InsertDatas<TEntity>(string connectionStrings, List<TEntity> model) where TEntity : class, new();
/// <summary>
/// 添加数据(json数组模式)
/// </summary>
/// <param name="connectionStrings">要连接的数据库</param>
/// <param name="recordList">待添加数据列表</param>
/// <param name="tableName">表名</param>
/// <returns></returns>
Task<bool> InsertData(string connectionStrings, List<Dictionary<string, object>> recordList,string tableName);
/// <summary>
/// 添加数据(json模式)
/// </summary>
/// <param name="connectionStrings">要连接的数据库</param>
/// <param name="record">待添加数据</param>
/// <param name="tableName">表名</param>
/// <returns></returns>
Task<bool> InsertData(string connectionStrings, Dictionary<string, object> record, string tableName);
/// <summary>
/// 查询单条数据
/// </summary>
/// <typeparam name="TEntity">数据库实体</typeparam>
/// <param name="connectionStrings">要连接的数据库</param>
/// <param name="whereExpression">查询条件</param>
/// <returns></returns>
Task<TEntity> QueryData<TEntity>(string connectionStrings, Expression<Func<TEntity, bool>> whereExpression, Expression<Func<TEntity, object>> orderby=null,OrderByType orderByType=0);
/// <summary>
/// 查询数据列表
/// </summary>
/// <typeparam name="TEntity">数据库实体</typeparam>
/// <param name="connectionStrings">要连接的数据库</param>
/// <param name="whereExpression">查询条件</param>
/// <returns></returns>
Task<List<TEntity>> QueryDataList<TEntity>(string connectionStrings, Expression<Func<TEntity, bool>> whereExpression, Expression<Func<TEntity, object>> orderby = null, OrderByType orderByType = OrderByType.Asc);
/// <summary>
/// 查询指定值
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="connectionStrings">要连接的数据库</param>
/// <param name="where">查询条件</param>
/// <param name="column">目标值</param>
/// <returns></returns>
Task<string> QueryValue<TEntity>(string connectionStrings, Expression<Func<TEntity, bool>> where, Expression<Func<TEntity, string>> column);
/// <summary>
/// 查询指定值 分组模式
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="connectionStrings"></param>
/// <param name="where"></param>
/// <param name="column"></param>
/// <param name="group"></param>
/// <returns></returns>
Task<List<string>> QueryValueGroup<TEntity>(string connectionStrings, Expression<Func<TEntity, bool>> where, Expression<Func<TEntity, string>> column, Expression<Func<TEntity, object>> group, Expression<Func<TEntity, object>> orderby = null, OrderByType orderByType = OrderByType.Asc);
/// <summary>
/// 查询指定值集合
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="connectionStrings">要连接的数据库</param>
/// <param name="where">查询条件</param>
/// <param name="column">目标值</param>
/// <returns></returns>
Task<List<string>> QueryValues<TEntity>(string connectionStrings, Expression<Func<TEntity, bool>> where, Expression<Func<TEntity, string>> column);
/// <summary>
/// 更新指定数据
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="connectionStrings">要连接的数据库</param>
/// <param name="model">数据实体</param>
/// <param name="where">条件</param>
/// <returns></returns>
Task<bool> UpdateData<TEntity>(string connectionStrings, TEntity model, Expression<Func<TEntity, bool>> where) where TEntity : class, new();
/// <summary>
/// 更新指定数据 忽略某些字段
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="connectionStrings">要连接的数据库</param>
/// <param name="model">数据实体</param>
/// <param name="where">条件</param>
/// <param name="IgnoreColumn">要忽略的字段</param>
/// <returns></returns>
Task<bool> UpdateData<TEntity>(string connectionStrings, TEntity model, Expression<Func<TEntity, bool>> where, Expression<Func<TEntity, object>> IgnoreColumn) where TEntity : class, new();
/// <summary>
/// 更新指定数据 如果目标列不存在 则为插入本条数据
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="connectionStrings">要连接的数据库</param>
/// <param name="model">数据实体</param>
/// <param name="where">更新条件</param>
/// <param name="column">目标列</param>
/// <returns></returns>
Task<bool> UpdateData<TEntity>(string connectionStrings, TEntity model, Expression<Func<TEntity, bool>> where, Expression<Func<TEntity, string>> column) where TEntity : class, new();
/// <summary>
/// 更新数据(json数组模式)
/// </summary>
/// <param name="connectionStrings">要连接的数据库</param>
/// <param name="recordList">待添加数据列表</param>
/// <param name="tableName">表名</param>
/// <param name="whereColumns">更新条件键名</param>
/// <returns></returns>
Task<bool> UpdateData(string connectionStrings, List<Dictionary<string, object>> recordList, string tableName, string whereColumns);
/// <summary>
/// 更新数据(json模式)
/// </summary>
/// <param name="connectionStrings">要连接的数据库</param>
/// <param name="record">待添加数据</param>
/// <param name="tableName">表名</param>
/// <param name="whereColumns">更新条件键名</param>
/// <returns></returns>
Task<bool> UpdateData(string connectionStrings, Dictionary<string, object> record, string tableName, string whereColumns);
}
实现:
public class DAL_Services: IDAL_Services
{
private SqlSugarClient GetInstance(string connectionStrings)
{
//创建数据库对象
SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
{
//根据传过来的枚举数据库连接找到对应的数据库
ConnectionString = AppConfigurtaionServices.Configuration.GetSection(connectionStrings).Value,
DbType = DbType.MySql,
IsAutoCloseConnection = true,//开启自动释放模式
InitKeyType = InitKeyType.Attribute//从特性读取主键自增信息
});
//添加Sql打印事件,开发中可以删掉这个代码
db.Aop.OnLogExecuting = (sql, pars) =>
{
Console.WriteLine(sql + "\r\n" + db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
Console.Write("sql执行时间:" + db.Ado.SqlExecutionTime.TotalSeconds.ToString());//输出SQL执行时间
Console.WriteLine();
};
return db;
}
public async Task<TEntity> QueryData<TEntity>(string connectionStrings, Expression<Func<TEntity, bool>> whereExpression, Expression<Func<TEntity, object>> orderby=null,OrderByType orderByType=OrderByType.Asc)
{
var db = GetInstance(connectionStrings);//获取SqlSugarClient
return await db.Queryable<TEntity>().WhereIF(whereExpression != null, whereExpression).OrderByIF(orderby!=null,orderby,orderByType).FirstAsync();
}
public async Task<List<TEntity>> QueryDataList<TEntity>(string connectionStrings,Expression<Func<TEntity, bool>> whereExpression, Expression<Func<TEntity, object>> orderby = null, OrderByType orderByType = OrderByType.Asc)
{
var db = GetInstance(connectionStrings);//获取SqlSugarClient
return await db.Queryable<TEntity>().WhereIF(whereExpression != null, whereExpression).OrderByIF(orderby != null, orderby, orderByType).ToListAsync();
}
public async Task<bool> InsertData<TEntity>(string connectionStrings, TEntity model) where TEntity:class,new()
{
var db = GetInstance(connectionStrings);//获取SqlSugarClient
var i = await db.Insertable(model).ExecuteCommandAsync();
return i > 0;
}
public async Task<bool> InsertDatas<TEntity>(string connectionStrings,List<TEntity> model) where TEntity : class, new()
{
var db = GetInstance(connectionStrings);//获取SqlSugarClient
var i = await db.Insertable(model).ExecuteCommandAsync();
return i > 0;
}
public async Task<string> QueryValue<TEntity>(string connectionStrings, Expression<Func<TEntity, bool>> where, Expression<Func<TEntity, string>> column)
{
var db = GetInstance(connectionStrings);//获取SqlSugarClient
return await db.Queryable<TEntity>().Where(where).Select(column).FirstAsync();//查询单条
}
public async Task<List<string>> QueryValueGroup<TEntity>(string connectionStrings, Expression<Func<TEntity, bool>> where, Expression<Func<TEntity, string>> column, Expression<Func<TEntity, object>> group,Expression<Func<TEntity, object>> orderby = null, OrderByType orderByType = OrderByType.Asc)
{
var db = GetInstance(connectionStrings);//获取SqlSugarClient
return await db.Queryable<TEntity>().OrderByIF(orderby!=null,orderby,orderByType).GroupBy(group).Where(where).Select(column).ToListAsync();
}
public async Task<List<string>> QueryValues<TEntity>(string connectionStrings, Expression<Func<TEntity, bool>> where, Expression<Func<TEntity, string>> column)
{
var db = GetInstance(connectionStrings);//获取SqlSugarClient
return await db.Queryable<TEntity>().Where(where).Select(column).ToListAsync();
}
public async Task<bool> UpdateData<TEntity>(string connectionStrings, TEntity model, Expression<Func<TEntity, bool>> where) where TEntity : class, new()
{
var db = GetInstance(connectionStrings);//获取SqlSugarClient
var i= await db.Updateable(model).Where(where).ExecuteCommandAsync();
return i > 0;
}
public async Task<bool> UpdateData<TEntity>(string connectionStrings, TEntity model, Expression<Func<TEntity, bool>> where, Expression<Func<TEntity, string>> column) where TEntity : class, new()
{
//查询当前值是否存在
var targetColumn = await QueryValue(connectionStrings, where, column);
if (!string.IsNullOrEmpty(targetColumn))
{
return await UpdateData(connectionStrings, model,where);
}
else
{
return await InsertData(connectionStrings, model);
}
}
public async Task<bool> UpdateData<TEntity>(string connectionStrings, TEntity model, Expression<Func<TEntity, bool>> where, Expression<Func<TEntity, object>> IgnoreColumn) where TEntity : class, new()
{
var db = GetInstance(connectionStrings);//获取SqlSugarClient
var i = await db.Updateable(model).IgnoreColumns(IgnoreColumn).Where(where).ExecuteCommandAsync();
return i > 0;
}
public async Task<bool> InsertData(string connectionStrings, List<Dictionary<string, object>> recordList, string tableName)
{
var db = GetInstance(connectionStrings);//获取SqlSugarClient
var i =await db.Insertable(recordList).AS(tableName).ExecuteCommandAsync();
return i > 0;
}
public async Task<bool> InsertData(string connectionStrings, Dictionary<string, object> record, string tableName)
{
var db = GetInstance(connectionStrings);//获取SqlSugarClient
var i =await db.Insertable(record).AS(tableName).ExecuteCommandAsync();
return i > 0;
}
public async Task<bool> UpdateData(string connectionStrings, List<Dictionary<string, object>> recordList, string tableName,string whereColumns)
{
var db = GetInstance(connectionStrings);//获取SqlSugarClient
var i = await db.Updateable(recordList).AS(tableName).WhereColumns(whereColumns).ExecuteCommandAsync();
return i > 0;
}
public async Task<bool> UpdateData(string connectionStrings, Dictionary<string, object> record, string tableName, string whereColumns)
{
var db = GetInstance(connectionStrings);//获取SqlSugarClient
var i = await db.Updateable(record).AS(tableName).WhereColumns(whereColumns).ExecuteCommandAsync();
return i > 0;
}
}
配置文件读取类
/// <summary>
/// 类库读取配置文件
/// </summary>
public class AppConfigurtaionServices
{
public static IConfiguration Configuration { get; set; }
static AppConfigurtaionServices()
{
//ReloadOnChange = true 当appsettings.json被修改时重新加载
Configuration = new ConfigurationBuilder()
//.SetBasePath(Directory.GetCurrentDirectory())
//AppDomain.CurrentDomain.BaseDirectory是程序集基目录,所以appsettings.json,需要复制一份放在程序集目录下,
.SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
.Add(new JsonConfigurationSource { Path = "appsettings.json", ReloadOnChange = true })
.Build();
}
}
配置文件 appsettings.json
"ConnectionStrings": {
"DB1": "server=127.0.0.1;port=3306;database=testdb1;uid=root;pwd=123456;SslMode=none;",
"DB2": "server=127.0.0.1;port=3306;database=testdb2;uid=root;pwd=123456;SslMode=none;"
}
调用方式
await _DAL.QueryDataList<表实体>("ConnectionStrings:DB1", w => w.ID.Equals("1"));
注:
方法未经投入生产使用 仅供参考
封装了一些sqlsugar的常用方法 用来动态切换数据库和依赖注入 支持泛型的更多相关文章
- 记录对依赖注入的小小理解和autofac的简单封装
首先,我不是一个开发者,只是业余学习者.其次我的文化水平很低,写这个主要是记录一下当前对于这块的理解,因为对于一个低水平 的业余学习者来说,忘记是很平常的事,因为接触.应用的少,现在理解,可能过段时间 ...
- Spring.NET依赖注入框架学习--实例化容器常用方法
Spring.NET依赖注入框架学习---实例化容器常用方法 本篇学习实例化Spring.NET容器的俩种方式 1.通过XmlObjectFactory创建一个Spring.NET容器 IResour ...
- RecyclerViewSelectableAdapterDemo【封装BaseSelectableAdapter用于多选、单选,以及切换选中状态等功能】
版权声明:本文为HaiyuKing原创文章,转载请注明出处! 前言 记录封装单选.多选.切换选中状态的BaseSelectableAdapter基类,配合Recyclerview使用. 注意:此Dem ...
- rxjava封装,RxBus封装(上线项目集成,声明周期管理,处理溢出内存,支持同时多个请求。)
Github地址 RxLibrary工程:1.rxjava2 + retrofit2的封装,常用的请求(Get,Post,文件上传,文件下载),防止内存泄漏,简单便捷,支持自定义loading等属性. ...
- 4.6 .net core依赖注入的封装
现在流行的系统一般都采用依赖注入的实现方式,利用DI容器来直接获取所用到的类/接口的实例..net core也一样采用DI的方式,提供了DI容器的接口IServiceCollection,并提供了基于 ...
- 多封装,少开放。强烈建议C++标准添加class之间的注入机制
近日在改动了一下下引擎代码(为了自己的组件),发现有些接口是仅仅有特定类及其内部函数才去訪问,却不使用友元声明的形式进行数据訪问--当然使用了普通非virtual的形式也就是意味着不建议重载. 故此: ...
- (7)学习笔记 ) ASP.NET CORE微服务 Micro-Service ---- 利用Polly+AOP+依赖注入封装的降级框架
创建简单的熔断降级框架 要达到的目标是: 参与降级的方法参数要一样,当HelloAsync执行出错的时候执行HelloFallBackAsync方法. public class Person { [H ...
- c++动态库封装及调用(3、windows下动态库调用)
1.DLL的隐式调用 隐式链接采用静态加载的方式,比较简单,需要.h..lib..dll三件套.新建“控制台应用程序”或“空项目”.配置如下: 项目->属性->配置属性->VC++ ...
- c++动态库封装及调用(2、windows下动态库创建)
DLL即动态链接库(Dynamic-Link Libaray)的缩写,相当于Linux下的共享对象.Windows系统中大量采用了DLL机制,甚至内核的结构很大程度依赖与DLL机制.Windows下的 ...
随机推荐
- CSS轮廓和圆角
1 2 <!DOCTYPE html> 3 <html lang="en"> 4 <head> 5 <meta charset=" ...
- redis雪崩,穿透,击穿
缓存雪崩:同一时间大量key到过期时间失效,可在设置失效时间时加随机数,如果直接修改数据库,那么一定会有不一致,通过失效时间去反复刷新缩短不一致的时间, 为了避免数据一直存在,一定要设置过期时间如果通 ...
- 【linux】驱动-4-LED芯片手册分析
目录 前言 4. LED芯片手册分析 4.1 内存管理单元MMU 4.1.1 MMU的功能 4.1.2 TLB的作用 4.2 地址转换函数 4.2.1 ioremap函数 4.2.2 iounmap函 ...
- 学习笔记-ionic3 环境配置搭建到打包
折腾了两周总算理清楚了,参考的链接如下: https://blog.csdn.net/zeternityyt/article/details/79655150 环境配置 https://segmen ...
- python3使用myqr生成链接二维码
技术背景 二维码技术在各个领域中都已经有非常成熟的应用,比如随处可见的二维码支付,比如疫情期间的绿码,再比如工业领域中,可以使用二维码作为定位的标签,大大提升了室内定位技术的精确度.二维码的格式内容大 ...
- nginx配置实例及多服务器负载
目录 nginx配置实例 多服务器负载 nginx配置实例 nginx.conf worker_processes 1; events { worker_connections 1024; } htt ...
- Lua OpenResty容器化(考古历程)
原文地址:Lua OpenResty容器化(考古历程) 背景 公司有几个"远古时期"的项目,一直都相对较为稳定,但是项目每天总会在一些时段,请求每分钟QPS到达峰值800K左右,导 ...
- 10. linux 系统启动流程
POST-->BIOS(Boot Sequence)-->MBR(bootloader,446)-->Kernel-->initrd-->(ROOTFS)/sbin/in ...
- Message Decoding UVA - 213
Some message encoding schemes require that an encoded message be sent in two parts. The fifirst par ...
- img 的data-src 属性及懒加载
一.什么是图片懒加载 当访问一个页面的时候,先把img元素或是其他元素的背景图片路径替换成一张大小为1*1px图片的路径(这样就只需请求一次),当图片出现在浏览器的可视区域内时,才设置图片真正的路径, ...