using Dapper; using Dapper.Contrib.Extensions; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Data; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text; using System.Threading.Tasks; using Znyc.Recruitment.Admin.Commons.Core.Dapper; using Znyc.Recruitment.Admin.Commons.Core.DataManager; using Znyc.Recruitment.Admin.Commons.DataManager; using Znyc.Recruitment.Admin.Commons.DependencyInjection; using Znyc.Recruitment.Admin.Commons.Entitys; using Znyc.Recruitment.Admin.Commons.Enums; using Znyc.Recruitment.Admin.Commons.IDbContext; using Znyc.Recruitment.Admin.Commons.IRepositories; using Znyc.Recruitment.Admin.Commons.Log; using Znyc.Recruitment.Admin.Commons.Pages; namespace Znyc.Recruitment.Admin.Commons.Repositories { /// /// 泛型仓储,实现泛型仓储接口 /// /// 实体类型 /// 实体主键类型 public abstract class BaseRepository : IRepository, ITransientDependency where T : Entity { #region 构造函数及基本配置 /// /// EF DBContext /// private readonly IDbContextCore _dbContext; private readonly IDbContextFactory _dbContextFactory; /// /// protected DbSet DbSet => DbContext.GetDbSet(); /// /// 获取访问数据库配置 /// protected DbConnectionOptions dbConnectionOptions = DBServerProvider.GeDbConnectionOptions(); /// /// 需要初始化的对象表名 /// protected string tableName = typeof(T).GetCustomAttribute(false)?.Name; /// /// 数据库参数化访问的占位符 /// protected string parameterPrefix = "@"; /// /// 防止和保留字、关键字同名的字段格式,如[value] /// protected string safeFieldFormat = "[{0}]"; /// /// 数据库的主键字段名,若主键不是Id请重载BaseRepository设置 /// protected string primaryKey = "Id"; /// /// 排序字段 /// protected string sortField; /// /// 是否为降序 /// protected bool isDescending = true; /// /// 选择的字段,默认为所有(*) /// protected string selectedFields = " * "; /// /// 是否开启多租户 /// protected bool isMultiTenant = false; /// /// 排序字段 /// public string SortField { get => sortField; set => sortField = value; } public string PrimaryKey => primaryKey; /// /// 构造方法 /// public BaseRepository() { } /// /// 构造方法,注入上下文 /// /// 上下文 public BaseRepository(IDbContextCore dbContext) { if (dbContext == null) { throw new ArgumentNullException(nameof(dbContext)); } _dbContext = dbContext; } /// /// 构造方法,注入上下文 /// /// 上下文 public BaseRepository(IDbContextFactory dbContextFactory) { _dbContextFactory = dbContextFactory; } #endregion 构造函数及基本配置 #region Dapper 操作 /// /// 用Dapper原生方法操作数据,支持读写操作 /// public IDbConnection DapperConn => new DapperDbContext().GetConnection(); /// /// 用Dapper原生方法,仅用于只读数据库 /// public IDbConnection DapperConnRead => new DapperDbContext().GetConnection(false); #region 查询获得对象和列表 /// /// 根据id获取一个对象 /// /// 主键 /// public virtual T Get(TKey primaryKey) { return DapperConnRead.Get(primaryKey); } /// /// 异步根据id获取一个对象 /// /// 主键 /// public virtual async Task GetAsync(TKey primaryKey) { return await DapperConnRead.GetAsync(primaryKey); } /// /// 根据条件获取一个对象 /// /// 查询条件 /// public virtual T GetWhere(string where) { if (HasInjectionData(where)) { Log4NetHelper.Info(string.Format("检测出SQL注入的恶意数据, {0}", where)); throw new Exception("检测出SQL注入的恶意数据"); } if (string.IsNullOrEmpty(where)) { @where = "1=1"; } string sql = $"select * from {tableName} "; sql += " where " + where; return DapperConnRead.QueryFirstOrDefault(sql); } /// /// 根据条件异步获取一个对象 /// /// 查询条件 /// public virtual async Task GetWhereAsync(string where) { if (HasInjectionData(where)) { Log4NetHelper.Info(string.Format("检测出SQL注入的恶意数据, {0}", where)); throw new Exception("检测出SQL注入的恶意数据"); } if (string.IsNullOrEmpty(where)) { @where = "1=1"; } string sql = $"select * from {tableName} "; sql += " where " + where; return await DapperConnRead.QueryFirstOrDefaultAsync(sql); } /// /// 获取所有数据,谨慎使用 /// /// 事务 /// public virtual IEnumerable GetAll(IDbTransaction trans = null) { return GetListWhere(); } /// /// 获取所有数据,谨慎使用 /// /// /// public virtual async Task> GetAllAsync(IDbTransaction trans = null) { return await GetListWhereAsync(); } /// /// 根据查询条件获取数据集合 /// /// 查询条件 /// 事务对象 /// public virtual IEnumerable GetListWhere(string where = null, IDbTransaction trans = null) { if (HasInjectionData(where)) { Log4NetHelper.Info(string.Format("检测出SQL注入的恶意数据, {0}", where)); throw new Exception("检测出SQL注入的恶意数据"); } string sql = $"select {selectedFields} from {tableName} "; if (!string.IsNullOrWhiteSpace(where)) { sql += " where " + @where; } return DapperConnRead.Query(sql, trans); } /// /// 根据查询条件获取数据集合 /// /// 查询条件 /// 事务对象 /// public virtual async Task> GetListWhereAsync(string where = null, IDbTransaction trans = null) { if (HasInjectionData(where)) { Log4NetHelper.Info(string.Format("检测出SQL注入的恶意数据, {0}", where)); throw new Exception("检测出SQL注入的恶意数据"); } string sql = $"select {selectedFields} from {tableName} where IsDeleted=0"; if (!string.IsNullOrWhiteSpace(where)) { sql += " and" + @where; } return await DapperConnRead.QueryAsync(sql, trans); } /// /// 根据查询条件查询前多少条数据 /// /// 多少条数据 /// 查询条件 /// 事务对象 /// public virtual IEnumerable GetListTopWhere(int top, string where = null, IDbTransaction trans = null) { if (HasInjectionData(where)) { Log4NetHelper.Info(string.Format("检测出SQL注入的恶意数据, {0}", where)); throw new Exception("检测出SQL注入的恶意数据"); } string sql = $"select top {top} {selectedFields} from " + tableName; ; if (dbConnectionOptions.DatabaseType == DatabaseType.SqlServer) { if (!string.IsNullOrWhiteSpace(where)) { sql += " where " + @where; } } else if (dbConnectionOptions.DatabaseType == DatabaseType.MySql) { sql = $"select {selectedFields} from " + tableName; if (!string.IsNullOrWhiteSpace(where)) { sql += " where " + @where; } sql += $" LIMIT 0,{top}; "; } return DapperConnRead.Query(sql, trans); } /// /// 根据查询条件查询前多少条数据 /// /// 多少条数据 /// 查询条件 /// 事务对象 /// public virtual async Task> GetListTopWhereAsync(int top, string where = null, IDbTransaction trans = null) { if (HasInjectionData(where)) { Log4NetHelper.Info(string.Format("检测出SQL注入的恶意数据, {0}", where)); throw new Exception("检测出SQL注入的恶意数据"); } string sql = $"select top {top} {selectedFields} from " + tableName; if (dbConnectionOptions.DatabaseType == DatabaseType.SqlServer) { if (!string.IsNullOrWhiteSpace(where)) { sql += " where " + @where; } } else if (dbConnectionOptions.DatabaseType == DatabaseType.MySql) { sql = $"select {selectedFields} from " + tableName; if (!string.IsNullOrWhiteSpace(where)) { sql += " where " + @where; } sql += $" LIMIT 0,{top}; "; } return await DapperConnRead.QueryAsync(sql, trans); } /// /// 查询软删除的数据,如果查询条件为空,即查询所有软删除的数据 /// /// 查询条件 /// 事务对象 /// public virtual IEnumerable GetAllByIsIsDeleted(string where = null, IDbTransaction trans = null) { if (HasInjectionData(where)) { Log4NetHelper.Info(string.Format("检测出SQL注入的恶意数据, {0}", where)); throw new Exception("检测出SQL注入的恶意数据"); } string sqlWhere = " IsDeleted=1 "; if (!string.IsNullOrWhiteSpace(where)) { sqlWhere += " and " + @where; } return GetListWhere(sqlWhere, trans); } /// /// 查询未软删除的数据,如果查询条件为空,即查询所有未软删除的数据 /// /// 查询条件 /// 事务对象 /// public virtual IEnumerable GetAllByIsNotIsDeleted(string where = null, IDbTransaction trans = null) { if (HasInjectionData(where)) { Log4NetHelper.Info(string.Format("检测出SQL注入的恶意数据, {0}", where)); throw new Exception("检测出SQL注入的恶意数据"); } string sqlWhere = " IsDeleted=0 "; if (!string.IsNullOrWhiteSpace(where)) { sqlWhere += " and " + @where; } return GetListWhere(sqlWhere, trans); } /// /// 查询有效的数据,如果查询条件为空,即查询所有有效的数据 /// /// 查询条件 /// 事务对象 /// public virtual IEnumerable GetAllByIsEnabledMark(string where = null, IDbTransaction trans = null) { if (HasInjectionData(where)) { Log4NetHelper.Info(string.Format("检测出SQL注入的恶意数据, {0}", where)); throw new Exception("检测出SQL注入的恶意数据"); } string sqlWhere = " IsEnabled=1 "; if (!string.IsNullOrWhiteSpace(where)) { sqlWhere += " and " + @where; } return GetListWhere(sqlWhere, trans); } /// /// 查询无效的数据,如果查询条件为空,即查询所有无效的数据 /// /// 查询条件 /// 事务对象 /// public virtual IEnumerable GetAllByIsNotEnabledMark(string where = null, IDbTransaction trans = null) { if (HasInjectionData(where)) { Log4NetHelper.Info(string.Format("检测出SQL注入的恶意数据, {0}", where)); throw new Exception("检测出SQL注入的恶意数据"); } string sqlWhere = " IsEnabled=0 "; if (!string.IsNullOrWhiteSpace(where)) { sqlWhere += " and " + @where; } return GetListWhere(sqlWhere, trans); } /// /// 查询未软删除且有效的数据,如果查询条件为空,即查询所有数据 /// /// 查询条件 /// 事务对象 /// public virtual IEnumerable GetAllByIsNotDeleteAndEnabledMark(string where = null, IDbTransaction trans = null) { if (HasInjectionData(where)) { Log4NetHelper.Info(string.Format("检测出SQL注入的恶意数据, {0}", where)); throw new Exception("检测出SQL注入的恶意数据"); } string sqlWhere = " IsDeleted=0"; if (!string.IsNullOrWhiteSpace(where)) { sqlWhere += " and " + @where; } return GetListWhere(sqlWhere, trans); } /// /// 查询软删除的数据,如果查询条件为空,即查询所有软删除的数据 /// /// 查询条件 /// 事务对象 /// public virtual async Task> GetAllByIsIsDeletedAsync(string where = null, IDbTransaction trans = null) { if (HasInjectionData(where)) { Log4NetHelper.Info(string.Format("检测出SQL注入的恶意数据, {0}", where)); throw new Exception("检测出SQL注入的恶意数据"); } string sqlWhere = " IsDeleted=1"; if (!string.IsNullOrWhiteSpace(where)) { sqlWhere += " and " + @where; } return await GetListWhereAsync(sqlWhere, trans); } /// /// 查询未软删除的数据,如果查询条件为空,即查询所有未软删除的数据 /// /// 查询条件 /// 事务对象 /// public virtual async Task> GetAllByIsNotIsDeletedAsync(string where = null, IDbTransaction trans = null) { if (HasInjectionData(where)) { Log4NetHelper.Info(string.Format("检测出SQL注入的恶意数据, {0}", where)); throw new Exception("检测出SQL注入的恶意数据"); } string sqlWhere = " IsDeleted=0 "; if (!string.IsNullOrWhiteSpace(where)) { sqlWhere += " and " + @where; } return await GetListWhereAsync(sqlWhere, trans); } /// /// 查询有效的数据,如果查询条件为空,即查询所有有效的数据 /// /// 查询条件 /// 事务对象 /// public virtual async Task> GetAllByIsEnabledMarkAsync(string where = null, IDbTransaction trans = null) { if (HasInjectionData(where)) { Log4NetHelper.Info(string.Format("检测出SQL注入的恶意数据, {0}", where)); throw new Exception("检测出SQL注入的恶意数据"); } string sqlWhere = " IsEnabled=1 "; if (!string.IsNullOrWhiteSpace(where)) { sqlWhere += " and " + @where; } return await GetListWhereAsync(sqlWhere, trans); } /// /// 查询未软删除且有效的数据,如果查询条件为空,即查询所有数据 /// /// 查询条件 /// 事务对象 /// public virtual async Task> GetAllByIsNotDeleteAndEnabledMarkAsync(string where = null, IDbTransaction trans = null) { if (HasInjectionData(where)) { Log4NetHelper.Info(string.Format("检测出SQL注入的恶意数据, {0}", where)); throw new Exception("检测出SQL注入的恶意数据"); } string sqlWhere = " IsDeleted=0"; if (!string.IsNullOrWhiteSpace(where)) { sqlWhere += " and " + @where; } return await GetListWhereAsync(sqlWhere, trans); } /// /// 根据条件查询数据库,并返回对象集合(用于分页数据显示) /// /// 查询的条件 /// 分页实体 /// 事务对象 /// 指定对象的集合 public virtual List FindWithPager(string condition, PagerInfo info, IDbTransaction trans = null) { return FindWithPager(condition, info, SortField, isDescending, trans); } /// /// 根据条件查询数据库,并返回对象集合(用于分页数据显示) /// /// 查询的条件 /// 分页实体 /// 排序字段 /// 事务对象 /// 指定对象的集合 public virtual List FindWithPager(string condition, PagerInfo info, string fieldToSort, IDbTransaction trans = null) { return FindWithPager(condition, info, fieldToSort, isDescending, trans); } /// /// 根据条件查询数据库,并返回对象集合(用于分页数据显示) /// /// 查询的条件 /// 分页实体 /// 排序字段 /// 事务对象 /// 指定对象的集合 public virtual async Task> FindWithPagerAsync(string condition, PagerInfo info, string fieldToSort, IDbTransaction trans = null) { return await FindWithPagerAsync(condition, info, fieldToSort, isDescending, trans); } /// /// 根据条件查询数据库,并返回对象集合(用于分页数据显示) /// /// 查询的条件 /// 分页实体 /// 事务对象 /// 指定对象的集合 public virtual async Task> FindWithPagerAsync(string condition, PagerInfo info, IDbTransaction trans = null) { return await FindWithPagerAsync(condition, info, SortField, trans); } /// /// 根据条件查询数据库,并返回对象集合(用于分页数据显示) /// /// 查询的条件 /// 分页实体 /// 排序字段 /// 排序方式 true为desc,false为asc /// 事务对象 /// 指定对象的集合 public virtual List FindWithPager(string condition, PagerInfo info, string fieldToSort, bool desc, IDbTransaction trans = null) { List list = new List(); if (HasInjectionData(condition)) { Log4NetHelper.Info(string.Format("检测出SQL注入的恶意数据, {0}", condition)); throw new Exception("检测出SQL注入的恶意数据"); } if (string.IsNullOrEmpty(condition)) { condition = "1=1"; } PagerHelper pagerHelper = new PagerHelper(tableName, selectedFields, fieldToSort, info.PageSize, info.CurrenetPageIndex, desc, condition); string pageSql = pagerHelper.GetPagingSql(true, dbConnectionOptions.DatabaseType); pageSql += ";" + pagerHelper.GetPagingSql(false, dbConnectionOptions.DatabaseType); SqlMapper.GridReader reader = DapperConnRead.QueryMultiple(pageSql); info.RecordCount = reader.ReadFirst(); list = reader.Read().AsList(); return list; } /// /// 根据条件查询数据库,并返回对象集合(用于分页数据显示) /// /// 查询的条件 /// 分页实体 /// 排序字段 /// 排序方式 true为desc,false为asc /// 事务对象 /// 指定对象的集合 public virtual async Task> FindWithPagerAsync(string condition, PagerInfo info, string fieldToSort, bool desc, IDbTransaction trans = null) { List list = new List(); if (HasInjectionData(condition)) { Log4NetHelper.Info(string.Format("检测出SQL注入的恶意数据, {0}", condition)); throw new Exception("检测出SQL注入的恶意数据"); } if (string.IsNullOrEmpty(condition)) { condition = " IsDeleted=0 "; } PagerHelper pagerHelper = new PagerHelper(tableName, selectedFields, fieldToSort, info.PageSize, info.CurrenetPageIndex, desc, condition); string pageSql = pagerHelper.GetPagingSql(true, dbConnectionOptions.DatabaseType); pageSql += ";" + pagerHelper.GetPagingSql(false, dbConnectionOptions.DatabaseType); SqlMapper.GridReader reader = await DapperConnRead.QueryMultipleAsync(pageSql); info.RecordCount = reader.ReadFirst(); list = reader.Read().AsList(); return list; } /// /// 分页查询,自行封装sql语句(仅支持sql server) /// 非常复杂的查询,可在具体业务模块重写该方法 /// /// 查询条件 /// 分页信息 /// 排序字段 /// 排序方式 true为desc,false为asc /// /// public virtual List FindWithPagerSql(string condition, PagerInfo info, string fieldToSort, bool desc, IDbTransaction trans = null) { List list = new List(); if (HasInjectionData(condition)) { Log4NetHelper.Info(string.Format("检测出SQL注入的恶意数据, {0}", condition)); throw new Exception("检测出SQL注入的恶意数据"); } if (string.IsNullOrEmpty(condition)) { condition = "1=1"; } StringBuilder sb = new StringBuilder(); int startRows = (info.CurrenetPageIndex - 1) * info.PageSize + 1; //起始记录 int endNum = info.CurrenetPageIndex * info.PageSize; //结束记录 string strOrder = string.Format(" {0} {1}", fieldToSort, desc ? "DESC" : "ASC"); sb.AppendFormat("SELECT count(*) as RecordCount FROM (select {0} FROM {1} where {2}) AS main_temp;", primaryKey, tableName, condition); sb.AppendFormat( "SELECT * FROM ( SELECT ROW_NUMBER() OVER (order by {0}) AS rows ,{1} FROM {2} where {3}) AS main_temp where rows BETWEEN {4} and {5}", strOrder, selectedFields, tableName, condition, startRows, endNum); SqlMapper.GridReader reader = DapperConnRead.QueryMultiple(sb.ToString()); info.RecordCount = reader.ReadFirst(); list = reader.Read().AsList(); return list; } /// /// 分页查询,自行封装sql语句(仅支持sql server) /// 非常复杂的查询,可在具体业务模块重写该方法 /// /// 查询条件 /// 分页信息 /// 排序字段 /// 排序方式 true为desc,false为asc /// /// public virtual async Task> FindWithPagerSqlAsync(string condition, PagerInfo info, string fieldToSort, bool desc, IDbTransaction trans = null) { if (HasInjectionData(condition)) { Log4NetHelper.Info(string.Format("检测出SQL注入的恶意数据, {0}", condition)); throw new Exception("检测出SQL注入的恶意数据"); } if (string.IsNullOrEmpty(condition)) { condition = "1=1"; } StringBuilder sb = new StringBuilder(); int startRows = (info.CurrenetPageIndex - 1) * info.PageSize + 1; //起始记录 int endNum = info.CurrenetPageIndex * info.PageSize; //结束记录 string strOrder = string.Format(" {0} {1}", fieldToSort, desc ? "DESC" : "ASC"); sb.AppendFormat("SELECT count(*) as RecordCount FROM (select {0} FROM {1} where {2}) AS main_temp;", primaryKey, tableName, condition); sb.AppendFormat( "SELECT * FROM ( SELECT ROW_NUMBER() OVER (order by {0}) AS rows ,{1} FROM {2} where {3}) AS main_temp where rows BETWEEN {4} and {5}", strOrder, selectedFields, tableName, condition, startRows, endNum); SqlMapper.GridReader reader = await DapperConnRead.QueryMultipleAsync(sb.ToString()); info.RecordCount = reader.ReadFirst(); List list = reader.Read().AsList(); return list; } /// /// 分页查询包含用户信息(仅支持sql server) /// 查询主表别名为t1,用户表别名为t2,在查询字段需要注意使用t1.xxx格式,xx表示主表字段 /// 用户信息主要有用户账号:Account、昵称:UserName、真实姓名:RealName、头像:HeadIcon、手机号:MobilePhone /// 输出对象请在Dtos中进行自行封装,不能是使用实体Model类 /// /// 查询条件字段需要加表别名 /// 分页信息 /// 排序字段,也需要加表别名 /// 排序方式 /// 事务 /// public virtual List FindWithPagerRelationUser(string condition, PagerInfo info, string fieldToSort, bool desc, IDbTransaction trans = null) { if (HasInjectionData(condition)) { Log4NetHelper.Info(string.Format("检测出SQL注入的恶意数据, {0}", condition)); throw new Exception("检测出SQL注入的恶意数据"); } if (string.IsNullOrEmpty(condition)) { condition = "1=1"; } StringBuilder sb = new StringBuilder(); int startRows = (info.CurrenetPageIndex - 1) * info.PageSize + 1; //起始记录 int endNum = info.CurrenetPageIndex * info.PageSize; //结束记录 string strOrder = string.Format(" {0} {1}", fieldToSort, desc ? "DESC" : "ASC"); sb.AppendFormat( "SELECT count(*) as RecordCount FROM (select t1.{0} FROM {1} t1 inner join sys_adminuser t2 on t1.CreatedUserId = t2.Id where {2}) AS main_temp;", primaryKey, tableName, condition); sb.AppendFormat( "SELECT * FROM (SELECT ROW_NUMBER() OVER (order by {0}) AS rows ,t1.{1},t2.Account as Account,t2.UserName as UserName,t2.RealName as RealName,t2.HeadIcon as HeadIcon ,t2.MobilePhone as MobilePhone FROM {2} t1 inner join sys_adminuser t2 on t1.CreatedUserId = t2.Id " + "where {3}) AS main_temp where rows BETWEEN {4} and {5}", strOrder, selectedFields, tableName, condition, startRows, endNum); SqlMapper.GridReader reader = DapperConnRead.QueryMultiple(sb.ToString()); info.RecordCount = reader.ReadFirst(); List list = reader.Read().AsList(); return list; } /// /// 分页查询包含用户信息(仅支持sql server) /// 查询主表别名为t1,用户表别名为t2,在查询字段需要注意使用t1.xxx格式,xx表示主表字段 /// 用户信息主要有用户账号:Account、昵称:UserName、真实姓名:RealName、头像:HeadIcon、手机号:MobilePhone /// 输出对象请在Dtos中进行自行封装,不能是使用实体Model类 /// /// 查询条件字段需要加表别名 /// 分页信息 /// 排序字段,也需要加表别名 /// 排序方式 /// 事务 /// public virtual async Task> FindWithPagerRelationUserAsync(string condition, PagerInfo info, string fieldToSort, bool desc, IDbTransaction trans = null) { if (HasInjectionData(condition)) { Log4NetHelper.Info(string.Format("检测出SQL注入的恶意数据, {0}", condition)); throw new Exception("检测出SQL注入的恶意数据"); } if (string.IsNullOrEmpty(condition)) { condition = "1=1"; } StringBuilder sb = new StringBuilder(); int startRows = (info.CurrenetPageIndex - 1) * info.PageSize + 1; //起始记录 int endNum = info.CurrenetPageIndex * info.PageSize; //结束记录 string strOrder = string.Format(" {0} {1}", fieldToSort, desc ? "DESC" : "ASC"); sb.AppendFormat( "SELECT count(*) as RecordCount FROM (select t1.{0} FROM {1} t1 inner join sys_adminuser t2 on t1.CreatedUserId = t2.Id where {2}) AS main_temp;", primaryKey, tableName, condition); sb.AppendFormat( "SELECT * FROM (SELECT ROW_NUMBER() OVER (order by {0}) AS rows ,t1.{1},t2.Account as Account,t2.UserName as UserName,t2.RealName as RealName,t2.HeadIcon as HeadIcon ,t2.MobilePhone as MobilePhone FROM {2} t1 inner join sys_adminuser t2 on t1.CreatedUserId = t2.Id " + "where {3}) AS main_temp where rows BETWEEN {4} and {5}", strOrder, selectedFields, tableName, condition, startRows, endNum); SqlMapper.GridReader reader = await DapperConnRead.QueryMultipleAsync(sb.ToString()); info.RecordCount = reader.ReadFirst(); List list = reader.Read().AsList(); return list; } /// /// 根据条件统计数据 /// /// 查询条件 /// 统计字段名称 /// public virtual int GetCountByWhere(string condition, string fieldName = "*") { if (HasInjectionData(condition)) { Log4NetHelper.Info(string.Format("检测出SQL注入的恶意数据, {0}", condition)); throw new Exception("检测出SQL注入的恶意数据"); } if (string.IsNullOrEmpty(condition)) { condition = "1=1"; } string sql = $"select count({fieldName}) from {tableName} where "; if (!string.IsNullOrWhiteSpace(condition)) { sql = sql + condition; } return DapperConnRead.Query(sql).FirstOrDefault(); } /// /// 根据条件统计数据 /// /// 查询条件 /// 统计字段名称 /// public virtual async Task GetCountByWhereAsync(string condition, string fieldName = "*") { if (HasInjectionData(condition)) { Log4NetHelper.Info(string.Format("检测出SQL注入的恶意数据, {0}", condition)); throw new Exception("检测出SQL注入的恶意数据"); } if (string.IsNullOrEmpty(condition)) { condition = "1=1"; } string sql = $"select count({fieldName}) from {tableName} where IsDeleted=0 and "; if (!string.IsNullOrWhiteSpace(condition)) { sql = sql + condition; } return await DapperConnRead.QueryFirstAsync(sql); } /// /// 根据条件统计数据 /// /// public virtual async Task GetCount() { string sql = $"select count(*) from {tableName} where IsDeleted=0 "; return await DapperConnRead.QueryFirstAsync(sql); } /// /// 根据条件查询获取某个字段的最大值 /// /// 字段 /// 条件 /// 事务 /// 返回字段的最大值 public virtual async Task GetMaxValueByFieldAsync(string strField, string where, IDbTransaction trans = null) { string sql = $"select isnull(MAX({strField}),0) as maxVaule from {tableName} "; if (dbConnectionOptions.DatabaseType == DatabaseType.MySql) { sql = $"select if(isnull(MAX({strField})),0,MAX({strField})) as maxVaule from {tableName} "; } if (!string.IsNullOrEmpty(where)) { sql += " where " + @where; } return await DapperConnRead.QueryFirstAsync(sql); } /// /// 根据条件统计某个字段之和,sum(字段) /// /// 字段 /// 条件 /// 事务 /// 返回字段求和后的值 public virtual async Task GetSumValueByFieldAsync(string strField, string where, IDbTransaction trans = null) { string sql = $"select isnull(sum({strField}),0) as sumVaule from {tableName} "; if (dbConnectionOptions.DatabaseType == DatabaseType.MySql) { sql = $"select if(isnull(sum({strField})),0,sum({strField})) as sumVaule from {tableName} "; } if (!string.IsNullOrEmpty(where)) { sql += " where " + @where; } return await DapperConnRead.QueryFirstAsync(sql); } /// /// 查询无效的数据,如果查询条件为空,即查询所有无效的数据 /// /// 查询条件 /// 事务对象 /// public virtual async Task> GetAllByIsNotEnabledMarkAsync(string where = null, IDbTransaction trans = null) { if (HasInjectionData(where)) { Log4NetHelper.Info(string.Format("检测出SQL注入的恶意数据, {0}", where)); throw new Exception("检测出SQL注入的恶意数据"); } string sqlWhere = " EnabledMark=0"; if (!string.IsNullOrWhiteSpace(where)) { sqlWhere += " and " + @where; } return await GetListWhereAsync(sqlWhere, trans); } #endregion 查询获得对象和列表 #region 新增、修改和删除 /// /// 新增 /// /// /// 事务对象 /// public virtual long Insert(T entity, IDbTransaction trans = null) { return DapperConn.Insert(entity); } /// /// 异步新增 /// /// /// 事务对象 /// 1新增成功,0新增失败 public virtual async Task InsertAsync(T entity, IDbTransaction trans = null) { return await DapperConn.InsertAsync(entity); } /// /// 异步新增实体返回主键 /// /// /// /// public virtual async Task InsertReturnPrimaryKeyAsync(T entity, IDbTransaction trans = null) { return await DapperConn.InsertReturnPrimaryKeyAsync(entity); } /// /// 批量插入数据 /// /// /// 执行成功返回true,否则为false public virtual void Insert(List entities) { DbContext.BulkInsert(entities); } /// /// 更新 /// /// /// 主键 /// 事务对象 /// 执行成功返回true,否则为false public virtual bool Update(T entity, TKey primaryKey, IDbTransaction trans = null) { return DbContext.Edit(entity) > 0; } /// /// 更新 /// /// /// 事务对象 /// 执行成功返回true,否则为false public virtual bool Update(T entity, IDbTransaction trans = null) { return DbContext.Edit(entity) > 0; } /// /// /// /// /// 事务对象 /// 执行成功返回true,否则为false public virtual async Task UpdateAsync(T entity, TKey primaryKey, IDbTransaction trans = null) { return await DapperConn.UpdateAsync(entity); } /// /// 同步物理删除实体。 /// /// 实体 /// public virtual bool Delete(T entity) { DbContext.GetDbSet().Remove(entity); return DbContext.SaveChanges() > 0; } /// /// 异步物理删除实体。 /// /// 实体 /// 事务对象 /// public virtual async Task DeleteAsync(T entity, IDbTransaction trans = null) { DbContext.GetDbSet().Remove(entity); return await DbContext.SaveChangesAsync() > 0; } /// /// 物理删除信息 /// /// /// 事务对象 /// 执行成功返回true,否则为false public virtual bool Delete(TKey primaryKey, IDbTransaction trans = null) { List> param = new List>(); string sql = $"delete from {tableName} where " + PrimaryKey + "=@PrimaryKey"; Tuple tupel = new Tuple(sql, new { PrimaryKey = primaryKey }); param.Add(tupel); Tuple result = ExecuteTransaction(param); return result.Item1; } /// /// 异步物理删除信息 /// /// /// 事务对象 /// 执行成功返回true,否则为false public virtual async Task DeleteAsync(TKey primaryKey, IDbTransaction trans = null) { List> param = new List>(); string sql = $"delete from {tableName} where " + PrimaryKey + "=@PrimaryKey"; Tuple tupel = new Tuple(sql, new { PrimaryKey = primaryKey }); param.Add(tupel); Tuple result = await ExecuteTransactionAsync(param); return result.Item1; } /// /// 按主键批量删除 /// /// 主键Id List集合 /// 事务对象 /// 执行成功返回true,否则为false public virtual bool DeleteBatch(IList ids, IDbTransaction trans = null) { List> param = new List>(); string sql = $"delete from {tableName} where PrimaryKey in (@PrimaryKey)"; Tuple tupel = new Tuple(sql, new { PrimaryKey = ids }); param.Add(tupel); Tuple result = ExecuteTransaction(param); return result.Item1; } /// /// 按条件批量删除 /// /// 条件 /// 事务对象 /// 执行成功返回true,否则为false public virtual bool DeleteBatchWhere(string where, IDbTransaction trans = null) { if (HasInjectionData(where)) { Log4NetHelper.Info(string.Format("检测出SQL注入的恶意数据, {0}", where)); throw new Exception("检测出SQL注入的恶意数据"); } if (string.IsNullOrEmpty(where)) { @where = "1=1"; } List> param = new List>(); string sql = $"delete from {tableName} where " + where; Tuple tupel = new Tuple(sql, null); param.Add(tupel); Tuple result = ExecuteTransaction(param); return result.Item1; } /// /// 按条件批量删除 /// /// 条件 /// 事务对象 /// 执行成功返回true,否则为false public virtual async Task DeleteBatchWhereAsync(string where, IDbTransaction trans = null) { if (HasInjectionData(where)) { Log4NetHelper.Info(string.Format("检测出SQL注入的恶意数据, {0}", where)); throw new Exception("检测出SQL注入的恶意数据"); } if (string.IsNullOrEmpty(where)) { @where = "1=1"; } List> param = new List>(); string sql = $"delete from {tableName} where " + where; Tuple tupel = new Tuple(sql, null); param.Add(tupel); Tuple result = await ExecuteTransactionAsync(param); return result.Item1; } /// /// 根据指定对象的ID和用户ID,从数据库中删除指定对象(用于记录人员的操作日志) /// /// 指定对象的ID /// 用户ID /// 事务对象 /// 执行成功返回true,否则为false public virtual bool DeleteByUser(TKey primaryKey, int userId, IDbTransaction trans = null) { List> param = new List>(); string sql = $"delete from {tableName} where " + PrimaryKey + " = @PrimaryKey"; Tuple tupel = new Tuple(sql, new { PrimaryKey = primaryKey }); param.Add(tupel); Tuple result = ExecuteTransaction(param); return result.Item1; } /// /// 异步根据指定对象的ID和用户ID,从数据库中删除指定对象(用于记录人员的操作日志) /// /// 指定对象的ID /// 用户ID /// 事务对象 /// 执行成功返回true,否则为false public virtual async Task DeleteByUserAsync(TKey primaryKey, int userId, IDbTransaction trans = null) { List> param = new List>(); string sql = $"delete from {tableName} where " + PrimaryKey + " = @PrimaryKey"; Tuple tupel = new Tuple(sql, new { PrimaryKey = primaryKey }); param.Add(tupel); Tuple result = await ExecuteTransactionAsync(param); return result.Item1; } /// /// 逻辑删除信息,bl为true时将IsDeleted设置为1删除,bl为flase时将IsDeleted设置为10-恢复删除 /// /// true为不删除,false删除 /// 主键ID /// 操作用户 /// 事务对象 /// 执行成功返回true,否则为false public virtual bool DeleteSoft(bool bl, TKey primaryKey, long userId = 0, IDbTransaction trans = null) { string sql = $"update {tableName} set "; if (bl) { sql += "IsDeleted=0 "; } else { sql += "IsDeleted=1 "; } DateTime deleteTime = DateTime.Now; sql += ",ModifiedTime=@ModifiedTime where " + PrimaryKey + "=@PrimaryKey"; List> param = new List>(); Tuple tupel = new Tuple(sql, new { PrimaryKey = primaryKey, DeleteTime = deleteTime }); param.Add(tupel); Tuple result = ExecuteTransaction(param); return result.Item1; } /// /// 异步逻辑删除信息,bl为true时将IsDeleted设置为0删除,bl为flase时将IsDeleted设置为1-恢复删除 /// /// true为不删除,false删除 /// 主键ID /// 操作用户 /// 事务对象 /// 执行成功返回true,否则为false public virtual async Task DeleteSoftAsync(bool bl, TKey primaryKey, long userId = 0, IDbTransaction trans = null) { string sql = $"update {tableName} set "; if (bl) { sql += "IsDeleted=0 "; } else { sql += "IsDeleted=1 "; } DateTime deleteTime = DateTime.Now; sql += ",ModifiedTime=@ModifiedTime,ModifiedUserId=@ModifiedUserId where " + PrimaryKey + "=@PrimaryKey"; List> param = new List>(); Tuple tupel = new Tuple(sql, new { PrimaryKey = primaryKey, ModifiedTime = deleteTime, ModifiedUserId = userId }); param.Add(tupel); Tuple result = await ExecuteTransactionAsync(param); return result.Item1; } /// /// 异步批量软删除信息,bl为true时将IsDeleted设置为0删除,bl为flase时将IsDeleted设置为1-恢复删除 /// /// true为不删除,false删除 /// c /// 条件 /// 操作用户 /// 事务对象 /// public virtual async Task DeleteSoftBatchAsync(bool bl, string where, long userId = 0, IDbTransaction trans = null) { if (HasInjectionData(where)) { Log4NetHelper.Info(string.Format("检测出SQL注入的恶意数据, {0}", where)); throw new Exception("检测出SQL注入的恶意数据"); } if (string.IsNullOrEmpty(where)) { @where = "1=1"; } string sql = $"update {tableName} set "; if (bl) { sql += "IsDeleted=0 "; } else { sql += "IsDeleted=1 "; } DateTime deleteTime = DateTime.Now; sql += ",ModifiedTime=@ModifiedTime,ModifiedUserId=@ModifiedUserId where " + where; List> param = new List>(); Tuple tupel = new Tuple(sql, new { ModifiedTime = deleteTime, ModifiedUserId = userId }); param.Add(tupel); Tuple result = await ExecuteTransactionAsync(param); return result.Item1; } /// /// 设置数据有效性,将IsEnabled设置为1-有效,0-为无效 /// /// true为有效,false无效 /// 主键ID /// 操作用户 /// 事务对象 /// 执行成功返回true,否则为false public virtual bool SetEnabledMark(bool bl, TKey primaryKey, long userId = 0, IDbTransaction trans = null) { string sql = $"update {tableName} set "; if (bl) { sql += "IsEnabled=1 "; } else { sql += "IsEnabled=0 "; } DateTime ModifiedTime = DateTime.Now; sql += ",ModifiedTime=@ModifiedTime where " + PrimaryKey + "=@PrimaryKey"; List> param = new List>(); Tuple tupel = new Tuple(sql, new { PrimaryKey = primaryKey, ModifiedTime }); param.Add(tupel); Tuple result = ExecuteTransaction(param); return result.Item1; } /// /// 异步设置数据有效性,将IsEnabled设置为1:有效,0-为无效 /// /// true为有效,false无效 /// 主键ID /// 操作用户 /// 事务对象 /// 执行成功返回true,否则为false public virtual async Task SetEnabledMarkAsync(bool bl, TKey primaryKey, long userId = 0, IDbTransaction trans = null) { string sql = $"update {tableName} set "; if (bl) { sql += "IsEnabled=1 "; } else { sql += "IsEnabled=0 "; } if (!string.IsNullOrEmpty(userId.ToString())) { sql += ",ModifiedUserId='" + userId + "'"; } DateTime ModifiedTime = DateTime.Now; sql += ",ModifiedTime=@ModifiedTime where " + PrimaryKey + "=@PrimaryKey"; List> param = new List>(); Tuple tupel = new Tuple(sql, new { PrimaryKey, ModifiedTime }); param.Add(tupel); Tuple result = await ExecuteTransactionAsync(param); return result.Item1; } /// /// 异步按条件设置数据有效性,将IsEnabled设置为1:有效,0-为无效 /// /// true为有效,false无效 /// 条件 /// 操作用户 /// 事务对象 /// public virtual async Task SetEnabledMarkByWhereAsync(bool bl, string where, long userId = 0, IDbTransaction trans = null) { if (HasInjectionData(where)) { Log4NetHelper.Info(string.Format("检测出SQL注入的恶意数据, {0}", where)); throw new Exception("检测出SQL注入的恶意数据"); } if (string.IsNullOrEmpty(where)) { @where = "1=1"; } string sql = $"update {tableName} set "; if (bl) { sql += "IsEnabled=1 "; } else { sql += "IsEnabled=0 "; } if (!string.IsNullOrEmpty(userId.ToString())) { sql += ",ModifiedUserId='" + userId + "'"; } DateTime ModifiedTime = DateTime.Now; sql += ",ModifiedTime=@ModifiedTime where " + where; List> param = new List>(); Tuple tupel = new Tuple(sql, new { ModifiedTime }); param.Add(tupel); Tuple result = await ExecuteTransactionAsync(param); return result.Item1; } /// /// 异步按条件设置数据的状态,将Status设置为0:审核中,1:正常,-1:停用,-2:停用 /// /// 0:审核中,1:正常,-1:停用,-2:停用 /// 条件 /// 操作用户 /// 事务对象 /// public virtual async Task SetStatusByWhereAsync(int bl, string where, long userId = 0, IDbTransaction trans = null) { if (HasInjectionData(where)) { Log4NetHelper.Info(string.Format("检测出SQL注入的恶意数据, {0}", where)); throw new Exception("检测出SQL注入的恶意数据"); } if (string.IsNullOrEmpty(where)) { @where = "1=1"; } string sql = $"update {tableName} set "; if (bl == (int)CommonStatus.REVIEW) { sql += "Status=0 "; } else if (bl == (int)CommonStatus.ENABLE) { sql += "Status=1 "; } else if (bl == (int)CommonStatus.DISABLE) { sql += "Status=-1 "; } else { sql += "Status=-2 "; } if (!string.IsNullOrEmpty(userId.ToString())) { sql += ",ModifiedUserId='" + userId + "'"; } DateTime ModifiedTime = DateTime.Now; sql += ",ModifiedTime=@ModifiedTime where " + where; List> param = new List>(); Tuple tupel = new Tuple(sql, new { ModifiedTime }); param.Add(tupel); Tuple result = await ExecuteTransactionAsync(param); return result.Item1; } /// /// 异步按条件设置数据有效性,将IsEnabled设置为1:有效,0-为无效 /// /// true为有效,false无效 /// 条件 /// /// /// /// public virtual async Task SetEnabledMarkByWhereAsync(bool bl, string where, object paramparameters = null, long userId = 0, IDbTransaction trans = null) { if (HasInjectionData(where)) { Log4NetHelper.Info(string.Format("检测出SQL注入的恶意数据, {0}", where)); throw new Exception("检测出SQL注入的恶意数据"); } if (string.IsNullOrEmpty(where)) { @where = "1=1"; } string sql = $"update {tableName} set "; if (bl) { sql += "IsEnabled=1 "; } else { sql += "IsEnabled=0 "; } if (!string.IsNullOrEmpty(userId.ToString())) { sql += ",ModifiedUserId='" + userId + "'"; } DateTime ModifiedTime = DateTime.Now; sql += ",ModifiedTime=@ModifiedTime " + where; List> param = new List>(); Tuple tupel = new Tuple(sql, new { ModifiedTime, paramparameters }); param.Add(tupel); Tuple result = await ExecuteTransactionAsync(param); return result.Item1; } /// /// 更新某一字段值,字段值字符类型 /// /// 字段 /// 字段值字符类型 /// 条件,为空更新所有内容 /// 事务对象 /// 执行成功返回true,否则为false public virtual bool UpdateTableField(string strField, string fieldValue, string where, IDbTransaction trans = null) { if (HasInjectionData(where)) { Log4NetHelper.Info(string.Format("检测出SQL注入的恶意数据, {0}", where)); throw new Exception("检测出SQL注入的恶意数据"); } if (string.IsNullOrEmpty(where)) { @where = "1=1"; } string sql = $"update {tableName} set " + strField + "='" + fieldValue + "'"; if (!string.IsNullOrEmpty(where)) { sql += " where " + @where; } List> param = new List>(); Tuple tupel = new Tuple(sql, null); param.Add(tupel); Tuple result = ExecuteTransaction(param); return result.Item1; } /// /// 更新某一字段值,字段值字符类型 /// /// 字段 /// 字段值字符类型 /// 条件,为空更新所有内容 /// 事务对象 /// 执行成功返回true,否则为false public virtual async Task UpdateTableFieldAsync(string strField, string fieldValue, string where, IDbTransaction trans = null) { if (HasInjectionData(where)) { Log4NetHelper.Info(string.Format("检测出SQL注入的恶意数据, {0}", where)); throw new Exception("检测出SQL注入的恶意数据"); } if (string.IsNullOrEmpty(where)) { @where = "1=1"; } string sql = $"update {tableName} set " + strField + "='" + fieldValue + "'"; if (!string.IsNullOrEmpty(where)) { sql += " where " + @where; } List> param = new List>(); Tuple tupel = new Tuple(sql, null); param.Add(tupel); Tuple result = await ExecuteTransactionAsync(param); return result.Item1; } /// /// 更新某一字段值,字段值为数字 /// /// 字段 /// 字段值数字 /// 条件,为空更新所有内容 /// 事务对象 /// 执行成功返回true,否则为false public virtual bool UpdateTableField(string strField, int fieldValue, string where, IDbTransaction trans = null) { if (HasInjectionData(where)) { Log4NetHelper.Info(string.Format("检测出SQL注入的恶意数据, {0}", where)); throw new Exception("检测出SQL注入的恶意数据"); } if (string.IsNullOrEmpty(where)) { @where = "1=1"; } string sql = $"update {tableName} set " + strField + "=" + fieldValue + ""; if (!string.IsNullOrEmpty(where)) { sql += " where " + @where; } List> param = new List>(); Tuple tupel = new Tuple(sql, null); param.Add(tupel); Tuple result = ExecuteTransaction(param); return result.Item1; } /// /// 更新某一字段值,字段值为数字 /// /// 字段 /// 字段值数字 /// 条件,为空更新所有内容 /// 事务对象 /// 执行成功返回true,否则为false public virtual async Task UpdateTableFieldAsync(string strField, int fieldValue, string where, IDbTransaction trans = null) { if (HasInjectionData(where)) { Log4NetHelper.Info(string.Format("检测出SQL注入的恶意数据, {0}", where)); throw new Exception("检测出SQL注入的恶意数据"); } if (string.IsNullOrEmpty(where)) { @where = "1=1"; } string sql = $"update {tableName} set " + strField + "=" + fieldValue + ""; if (!string.IsNullOrEmpty(where)) { sql += " where " + @where; } List> param = new List>(); Tuple tupel = new Tuple(sql, null); param.Add(tupel); Tuple result = await ExecuteTransactionAsync(param); return result.Item1; } /// /// 多表多数据操作批量插入、更新、删除--事务 /// /// 事务 /// 超时 /// public async Task> ExecuteTransactionAsync(List> trans, int? commandTimeout = null) { if (!trans.Any()) { return new Tuple(false, "执行事务SQL语句不能为空!"); } using (IDbConnection connection = DapperConn) { bool isClosed = connection.State == ConnectionState.Closed; if (isClosed) { connection.Open(); } using (IDbTransaction transaction = connection.BeginTransaction()) { try { foreach (Tuple tran in trans) { await connection.ExecuteAsync(tran.Item1, tran.Item2, transaction, commandTimeout); } //提交事务 transaction.Commit(); return new Tuple(true, string.Empty); } catch (Exception ex) { //回滚事务 Log4NetHelper.Error("", ex); transaction.Rollback(); connection.Close(); connection.Dispose(); DapperConn.Close(); DapperConn.Dispose(); throw ex; } finally { connection.Close(); connection.Dispose(); DapperConn.Close(); DapperConn.Dispose(); } } } } /// /// 多表多数据操作批量插入、更新、删除--事务 /// /// 事务 /// 超时 /// public Tuple ExecuteTransaction(List> trans, int? commandTimeout = null) { if (!trans.Any()) { return new Tuple(false, "执行事务SQL语句不能为空!"); } using (IDbConnection connection = DapperConn) { bool isClosed = connection.State == ConnectionState.Closed; if (isClosed) { connection.Open(); } //开启事务 using (IDbTransaction transaction = connection.BeginTransaction()) { try { foreach (Tuple tran in trans) { connection.Execute(tran.Item1, tran.Item2, transaction, commandTimeout); } //提交事务 transaction.Commit(); return new Tuple(true, string.Empty); } catch (Exception ex) { //回滚事务 Log4NetHelper.Error("", ex); transaction.Rollback(); connection.Close(); connection.Dispose(); DapperConn.Close(); DapperConn.Dispose(); return new Tuple(false, ex.ToString()); } finally { connection.Close(); connection.Dispose(); DapperConn.Close(); DapperConn.Dispose(); } } } } #endregion 新增、修改和删除 #endregion Dapper 操作 #region EF操作 /// /// EF 上下文接口,可读可写 /// public virtual IDbContextCore DbContext => _dbContext; /// /// EF 上下文接口,仅可读 /// public virtual IDbContextCore DbContextRead => _dbContextFactory.CreateContext(WriteAndReadEnum.Read); #region 新增 /// /// 新增实体 /// /// /// public virtual int Add(T entity) { return DbContext.Add(entity); } /// /// 新增实体 /// /// /// public virtual async Task AddAsync(T entity) { return await DbContext.AddAsync(entity); } /// /// 批量新增实体,数量量较多是推荐使用BulkInsert() /// /// /// public virtual int AddRange(ICollection entities) { return DbContext.AddRange(entities); } /// /// 批量新增实体,数量量较多是推荐使用BulkInsert() /// /// /// public virtual async Task AddRangeAsync(ICollection entities) { return await DbContext.AddRangeAsync(entities); } /// /// 批量新增SqlBulk方式,效率最高 /// /// 数据实体集合 /// 数据库表名称,默认为实体名称 public virtual void BulkInsert(IList entities, string destinationTableName = null) { DbContext.BulkInsert(entities, destinationTableName); } /// /// 执行新增的sql语句 /// /// 新增Sql语句 /// public int AddBySql(string sql) { return DbContext.ExecuteSqlWithNonQuery(sql); } #endregion 新增 #region Update /// /// 更新数据实体 /// /// /// public virtual int Edit(T entity) { return DbContext.Edit(entity); } /// /// 批量更新数据实体 /// /// /// public virtual int EditRange(ICollection entities) { return DbContext.EditRange(entities); } /// /// 更新指定字段的值 /// /// 数据实体 /// 指定字段 /// public virtual int Update(T model, params string[] updateColumns) { DbContext.Update(model, updateColumns); return DbContext.SaveChanges(); } /// /// 执行更新数据的Sql语句 /// /// 更新数据的Sql语句 /// public int UpdateBySql(string sql) { return DbContext.ExecuteSqlWithNonQuery(sql); } #endregion Update #region Delete /// /// 根据主键删除数据 /// /// /// public virtual int Delete(TKey key) { return DbContext.Delete(key); } /// /// 执行删除数据Sql语句 /// /// 删除的Sql语句 /// public int DeleteBySql(string sql) { return DbContext.ExecuteSqlWithNonQuery(sql); } #endregion Delete #region Query /// /// 根据条件统计数量Count() /// /// /// public virtual int Count(Expression> where = null) { return DbContext.Count(where); } /// /// 根据条件统计数量Count() /// /// /// public virtual async Task CountAsync(Expression> where = null) { return await DbContext.CountAsync(where); } /// /// 是否存在,存在返回true,不存在返回false /// /// /// public virtual bool Exist(Expression> where = null) { return DbContext.Exist(where); } /// /// 是否存在,存在返回true,不存在返回false /// /// /// public virtual async Task ExistAsync(Expression> where = null) { return await DbContext.ExistAsync(where); } /// /// 根据主键获取实体。建议:如需使用Include和ThenInclude请重载此方法。 /// /// /// public virtual T GetSingle(TKey key) { return DbContext.Find(key); } /// /// 根据主键获取实体。建议:如需使用Include和ThenInclude请重载此方法。 /// /// /// public virtual async Task GetSingleAsync(TKey key) { return await DbContext.FindAsync(key); } /// /// 获取单个实体。建议:如需使用Include和ThenInclude请重载此方法。 /// /// /// public virtual T GetSingleOrDefault(Expression> where = null) { return DbContext.GetSingleOrDefault(where); } /// /// 获取单个实体。建议:如需使用Include和ThenInclude请重载此方法。 /// /// /// public virtual async Task GetSingleOrDefaultAsync(Expression> where = null) { return await DbContext.GetSingleOrDefaultAsync(where); } /// /// 获取实体列表。建议:如需使用Include和ThenInclude请重载此方法。 /// /// /// public virtual IList Get(Expression> where = null) { return DbContext.GetByCompileQuery(where); } /// /// 获取实体列表。建议:如需使用Include和ThenInclude请重载此方法。 /// /// /// public virtual async Task> GetAsync(Expression> where = null) { return await DbContext.GetByCompileQueryAsync(where); } /// /// 分页获取实体列表。建议:如需使用Include和ThenInclude请重载此方法。 /// /// 查询条件 /// 分页信息 /// 排序方式 /// 排序字段 /// public virtual IEnumerable GetByPagination(Expression> where, PagerInfo pagerInfo, bool asc = false, params Expression>[] orderby) { IQueryable filter = DbContext.Get(where); if (orderby != null) { foreach (Expression> func in @orderby) { filter = asc ? filter.OrderBy(func).AsQueryable() : filter.OrderByDescending(func).AsQueryable(); } } pagerInfo.RecordCount = filter.Count(); return filter.Skip(pagerInfo.PageSize * (pagerInfo.CurrenetPageIndex - 1)).Take(pagerInfo.PageSize); } /// /// sql语句查询数据集 /// /// /// public List GetBySql(string sql) { return DbContext.SqlQuery(sql); } /// /// sql语句查询数据集,返回输出Dto实体 /// /// /// /// public List GetViews(string sql) { List list = DbContext.SqlQuery(sql); return list; } /// /// 查询视图 /// /// 返回结果对象 /// 视图名称 /// 查询条件 /// public List GetViews(string viewName, Func where) { List list = DbContext.SqlQuery($"select * from {viewName}"); if (where != null) { return list.Where(@where).ToList(); } return list; } #endregion Query #endregion EF操作 #region 辅助类方法 /// /// 验证是否存在注入代码(条件语句) /// /// public virtual bool HasInjectionData(string inputData) { if (string.IsNullOrEmpty(inputData)) { return false; } //里面定义恶意字符集合 //验证inputData是否包含恶意集合 //if (Regex.IsMatch(inputData.ToLower(), GetRegexString())) //{ // return true; //} return false; } /// /// 获取正则表达式 /// /// private static string GetRegexString() { //构造SQL的注入关键字符 string[] strBadChar = { "select\\s", "from\\s", "insert\\s", "delete\\s", "update\\s", "drop\\s", "truncate\\s", "exec\\s", "count\\(", "declare\\s", "asc\\(", "mid\\(", //"char\\(", "net user", "xp_cmdshell", "/add\\s", "exec master.dbo.xp_cmdshell", "net localgroup administrators" }; //构造正则表达式 string str_Regex = ".*("; for (int i = 0; i < strBadChar.Length - 1; i++) { str_Regex += strBadChar[i] + "|"; } str_Regex += strBadChar[^1] + ").*"; return str_Regex; } #endregion 辅助类方法 #region IDisposable Support private bool disposedValue; // 要检测冗余调用 /// /// /// protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { // TODO: 释放托管状态(托管对象)。 } // TODO: 释放未托管的资源(未托管的对象)并在以下内容中替代终结器。 // TODO: 将大型字段设置为 null。 disposedValue = true; } if (DbContext != null) { DbContext.Dispose(); } if (DapperConn != null) { DapperConn?.Dispose(); } } // TODO: 仅当以上 Dispose(bool disposing) 拥有用于释放未托管资源的代码时才替代终结器。 // ~BaseRepository() { // // 请勿更改此代码。将清理代码放入以上 Dispose(bool disposing) 中。 // Dispose(false); // } /// /// public void Dispose() { // 请勿更改此代码。将清理代码放入以上 Dispose(bool disposing) 中。 Dispose(true); DbContext?.Dispose(); DapperConn?.Dispose(); // TODO: 如果在以上内容中替代了终结器,则取消注释以下行。 // GC.SuppressFinalize(this); } #endregion IDisposable Support } }