using EntrustSettle.IRepository.Base; using EntrustSettle.Model; using EntrustSettle.Repository.UnitOfWorks; using SqlSugar; using System; using System.Collections.Generic; using System.Data; using System.Linq.Expressions; using System.Reflection; using System.Threading.Tasks; namespace EntrustSettle.Repository.Base { public class BaseRepository : IBaseRepository where TEntity : class, new() { private readonly IUnitOfWorkManage _unitOfWorkManage; private readonly SqlSugarScope _dbBase; private ISqlSugarClient _db { get { ISqlSugarClient db = _dbBase; //参考 https://www.donet5.com/Home/Doc?typeId=2246 var tenantAttr = typeof(TEntity).GetCustomAttribute(); if (tenantAttr != null) { //统一处理 configId 小写 db = _dbBase.GetConnectionScope(tenantAttr.configId.ToString().ToLower()); return db; } return db; } } public ISqlSugarClient Db => _db; public BaseRepository(IUnitOfWorkManage unitOfWorkManage) { _unitOfWorkManage = unitOfWorkManage; _dbBase = unitOfWorkManage.GetDbClient(); } #region 查询 public async Task QueryById(object objId) { return await _db.Queryable().In(objId).SingleAsync(); } public async Task QueryById(object objId, bool blnUseCache = false) { return await _db.Queryable().WithCacheIF(blnUseCache, 10).In(objId).SingleAsync(); } public async Task> QueryByIDs(object[] lstIds) { return await _db.Queryable().In(lstIds).ToListAsync(); } public async Task QueryFirst(Expression> whereExpression) { return await _db.Queryable().Where(whereExpression).FirstAsync(); } public async Task QueryFirstInclude(Expression> whereExpression, Expression>> include) { return await _db.Queryable().Includes(include).Where(whereExpression).FirstAsync(); } public async Task> Query() { return await _db.Queryable().ToListAsync(); } public async Task> Query(Expression> whereExpression) { return await _db.Queryable().WhereIF(whereExpression != null, whereExpression).ToListAsync(); } public async Task> Query(Expression> whereExpression, Expression> orderByExpression, bool isAsc = true) { return await _db.Queryable() .OrderByIF(orderByExpression != null, orderByExpression, isAsc ? OrderByType.Asc : OrderByType.Desc) .WhereIF(whereExpression != null, whereExpression).ToListAsync(); } public async Task> Query(Expression> whereExpression, string orderByFields) { return await _db.Queryable().WhereIF(whereExpression != null, whereExpression) .OrderByIF(orderByFields != null, orderByFields).ToListAsync(); } public async Task> Query(string where, string orderByFields) { return await _db.Queryable().OrderByIF(!string.IsNullOrEmpty(orderByFields), orderByFields) .WhereIF(!string.IsNullOrEmpty(where), where).ToListAsync(); } public async Task> QueryTop(Expression> whereExpression, int top, string orderByFields) { return await _db.Queryable() .OrderByIF(!string.IsNullOrEmpty(orderByFields), orderByFields) .WhereIF(whereExpression != null, whereExpression) .Take(top) .ToListAsync(); } public async Task> QueryTop(string where, int top, string orderByFields) { return await _db.Queryable() .OrderByIF(!string.IsNullOrEmpty(orderByFields), orderByFields) .WhereIF(!string.IsNullOrEmpty(where), where) .Take(top) .ToListAsync(); } public async Task> QueryPage(Expression> whereExpression, int pageIndex, int pageSize, string orderByFields) { return await _db.Queryable() .OrderByIF(!string.IsNullOrEmpty(orderByFields), orderByFields) .WhereIF(whereExpression != null, whereExpression) .ToPageListAsync(pageIndex, pageSize); } public async Task> QueryPage(string where, int pageIndex, int pageSize, string orderByFields) { return await _db.Queryable() .OrderByIF(!string.IsNullOrEmpty(orderByFields), orderByFields) .WhereIF(!string.IsNullOrEmpty(where), where) .ToPageListAsync(pageIndex, pageSize); } public async Task> QueryPageModel(Expression> whereExpression, int pageIndex = 1, int pageSize = 20, Expression> orderByExpression = null, bool isAsc = true) { RefAsync totalCount = 0; List list = await _db.Queryable() .OrderByIF(orderByExpression is not null, orderByExpression, isAsc ? OrderByType.Asc : OrderByType.Desc) .WhereIF(whereExpression != null, whereExpression) .ToPageListAsync(pageIndex, pageSize, totalCount); return new PageModel(pageIndex, totalCount, pageSize, list); } public async Task> QueryPageModel(Expression> whereExpression, int pageIndex = 1, int pageSize = 20, string orderByFields = null) { RefAsync totalCount = 0; var list = await _db.Queryable() .OrderByIF(!string.IsNullOrEmpty(orderByFields), orderByFields) .WhereIF(whereExpression != null, whereExpression) .ToPageListAsync(pageIndex, pageSize, totalCount); return new PageModel(pageIndex, totalCount, pageSize, list); } public async Task> QueryDto(Expression> expression) { return await _db.Queryable().Select(expression).ToListAsync(); } public async Task> QueryDto(Expression> expression, Expression> whereExpression, string orderByFields) { return await _db.Queryable() .OrderByIF(!string.IsNullOrEmpty(orderByFields), orderByFields) .WhereIF(whereExpression != null, whereExpression) .Select(expression) .ToListAsync(); } public async Task> QuerySql(string sql, SugarParameter[] parameters = null) { return await _db.Ado.SqlQueryAsync(sql, parameters); } public async Task QueryTable(string sql, SugarParameter[] parameters = null) { return await _db.Ado.GetDataTableAsync(sql, parameters); } /// /// 两表联查 /// public async Task> QueryMuch(Expression> joinExpression, Expression> whereExpression, Expression> selectExpression) where T : class, new() { return await _db.Queryable(joinExpression) .WhereIF(whereExpression != null, whereExpression) .Select(selectExpression) .ToListAsync(); } /// /// 两表联合查询-分页 /// public async Task> QueryMuchPage(Expression> joinExpression, Expression> whereExpression, Expression> selectExpression, int pageIndex = 1, int pageSize = 20, string strOrderByFileds = null) { RefAsync totalCount = 0; List list = await _db.Queryable(joinExpression) .WhereIF(whereExpression != null, whereExpression) .OrderByIF(!string.IsNullOrEmpty(strOrderByFileds), strOrderByFileds) .Select(selectExpression) .ToPageListAsync(pageIndex, pageSize, totalCount); return new PageModel(pageIndex, totalCount, pageSize, list); } /// /// 两表联合查询-分页-分组 /// public async Task> QueryMuchPageGroup(Expression> joinExpression, Expression> whereExpression, Expression> selectExpression, Expression> groupExpression, int pageIndex = 1, int pageSize = 20, string strOrderByFileds = null) { RefAsync totalCount = 0; List list = await _db.Queryable(joinExpression) .WhereIF(whereExpression != null, whereExpression) .GroupBy(groupExpression) .OrderByIF(!string.IsNullOrEmpty(strOrderByFileds), strOrderByFileds) .Select(selectExpression) .ToPageListAsync(pageIndex, pageSize, totalCount); return new PageModel(pageIndex, totalCount, pageSize, list); } /// /// 三表联查 /// public async Task> QueryMuch( Expression> joinExpression, Expression> whereLambda, Expression> selectExpression) where T : class, new() { if (whereLambda == null) { return await _db.Queryable(joinExpression).Select(selectExpression).ToListAsync(); } return await _db.Queryable(joinExpression).Where(whereLambda).Select(selectExpression).ToListAsync(); } /// /// 三表联合查询-分页 /// public async Task> QueryMuchPage(Expression> joinExpression, Expression> whereExpression, Expression> selectExpression, int pageIndex = 1, int pageSize = 20, string strOrderByFileds = null) { RefAsync totalCount = 0; List list = await _db.Queryable(joinExpression) .WhereIF(whereExpression != null, whereExpression) .OrderByIF(!string.IsNullOrEmpty(strOrderByFileds), strOrderByFileds) .Select(selectExpression) .ToPageListAsync(pageIndex, pageSize, totalCount).ConfigureAwait(false); return new PageModel(pageIndex, totalCount, pageSize, list); } #endregion #region 新增 public async Task Add(TEntity entity) { var insert = _db.Insertable(entity); return await insert.ExecuteReturnSnowflakeIdAsync(); //这里你可以返回TEntity,这样的话就可以获取id值,无论主键是什么类型 //var return3 = await insert.ExecuteReturnEntityAsync(); } public async Task> Add(List listEntity) { return await _db.Insertable(listEntity.ToArray()).ExecuteReturnSnowflakeIdListAsync(); } #endregion #region 删除 public async Task Delete(TEntity entity) { return await _db.Deleteable(entity).ExecuteCommandHasChangeAsync(); } public async Task DeleteById(object id) { return await _db.Deleteable().In(id).ExecuteCommandHasChangeAsync(); } public async Task DeleteByIds(object[] ids) { return await _db.Deleteable().In(ids).ExecuteCommandHasChangeAsync(); } #endregion #region 更新 public async Task Update(TEntity entity) { ////这种方式会以主键为条件 //var i = await Task.Run(() => _db.Updateable(entity).ExecuteCommand()); //return i > 0; //这种方式会以主键为条件 return await _db.Updateable(entity).ExecuteCommandHasChangeAsync(); } public async Task Update(TEntity entity, Expression> updateColumns) { return await _db.Updateable(entity).UpdateColumns(updateColumns).ExecuteCommandHasChangeAsync(); } public async Task Update(List entity) { return await _db.Updateable(entity).ExecuteCommandHasChangeAsync(); } public async Task Update(TEntity entity, string where) { return await _db.Updateable(entity).Where(where).ExecuteCommandHasChangeAsync(); } public async Task Update(object operateAnonymousObjects) { return await _db.Updateable(operateAnonymousObjects).ExecuteCommandAsync() > 0; } public async Task Update(TEntity entity, List lstColumns = null, List lstIgnoreColumns = null, string where = "") { IUpdateable up = _db.Updateable(entity); if (lstIgnoreColumns != null && lstIgnoreColumns.Count > 0) { up = up.IgnoreColumns(lstIgnoreColumns.ToArray()); } if (lstColumns != null && lstColumns.Count > 0) { up = up.UpdateColumns(lstColumns.ToArray()); } if (!string.IsNullOrEmpty(where)) { up = up.Where(where); } return await up.ExecuteCommandHasChangeAsync(); } public async Task Update(Expression> columns, Expression> where) { return await _db.Updateable() .SetColumns(columns) .Where(where) .ExecuteCommandHasChangeAsync(); } #endregion #region Split分表基础接口 (基础CRUD) /// /// 分页查询 /// public async Task> QueryPageSplit(Expression> whereExpression, DateTime beginTime, DateTime endTime, int pageIndex = 1, int pageSize = 20, string orderByFields = null) { RefAsync totalCount = 0; var list = await _db.Queryable().SplitTable(beginTime, endTime) .OrderByIF(!string.IsNullOrEmpty(orderByFields), orderByFields) .WhereIF(whereExpression != null, whereExpression) .ToPageListAsync(pageIndex, pageSize, totalCount); var data = new PageModel(pageIndex, totalCount, pageSize, list); return data; } /// /// 写入实体数据 /// public async Task> AddSplit(TEntity entity) { var insert = _db.Insertable(entity).SplitTable(); //插入并返回雪花ID并且自动赋值ID  return await insert.ExecuteReturnSnowflakeIdListAsync(); } /// /// 更新实体数据 /// public async Task UpdateSplit(TEntity entity, DateTime dateTime) { //直接根据实体集合更新 (全自动 找表更新) //return await _db.Updateable(entity).SplitTable().ExecuteCommandAsync();//,SplitTable不能少 //精准找单个表 var tableName = _db.SplitHelper().GetTableName(dateTime); //根据时间获取表名 return await _db.Updateable(entity).AS(tableName).ExecuteCommandHasChangeAsync(); } /// /// 删除数据 /// /// /// /// public async Task DeleteSplit(TEntity entity, DateTime dateTime) { ////直接根据实体集合删除 (全自动 找表插入),返回受影响数 //return await _db.Deleteable(entity).SplitTable().ExecuteCommandAsync();//,SplitTable不能少 //精准找单个表 var tableName = _db.SplitHelper().GetTableName(dateTime); //根据时间获取表名 return await _db.Deleteable().AS(tableName).Where(entity).ExecuteCommandHasChangeAsync(); } /// /// 根据ID查找数据 /// /// /// public async Task QueryByIdSplit(object objId) { return await _db.Queryable().In(objId).SplitTable(tabs => tabs).SingleAsync(); } #endregion } }