You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

408 lines
20 KiB
C#

This file contains invisible Unicode characters!

This file contains invisible Unicode characters that may be processed differently from what appears below. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to reveal hidden characters.

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

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<TEntity> : IBaseRepository<TEntity> 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<TenantAttribute>();
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<TEntity> QueryById(object objId)
{
return await _db.Queryable<TEntity>().In(objId).SingleAsync();
}
public async Task<TEntity> QueryById(object objId, bool blnUseCache = false)
{
return await _db.Queryable<TEntity>().WithCacheIF(blnUseCache, 10).In(objId).SingleAsync();
}
public async Task<List<TEntity>> QueryByIDs(object[] lstIds)
{
return await _db.Queryable<TEntity>().In(lstIds).ToListAsync();
}
public async Task<TEntity> QueryFirst(Expression<Func<TEntity, bool>> whereExpression)
{
return await _db.Queryable<TEntity>().Where(whereExpression).FirstAsync();
}
public async Task<TEntity> QueryFirstInclude<TReturn>(Expression<Func<TEntity, bool>> whereExpression, Expression<Func<TEntity, List<TReturn>>> include)
{
return await _db.Queryable<TEntity>().Includes(include).Where(whereExpression).FirstAsync();
}
public async Task<List<TEntity>> Query()
{
return await _db.Queryable<TEntity>().ToListAsync();
}
public async Task<List<TEntity>> Query(Expression<Func<TEntity, bool>> whereExpression)
{
return await _db.Queryable<TEntity>().WhereIF(whereExpression != null, whereExpression).ToListAsync();
}
public async Task<List<TEntity>> Query(Expression<Func<TEntity, bool>> whereExpression, Expression<Func<TEntity, object>> orderByExpression, bool isAsc = true)
{
return await _db.Queryable<TEntity>()
.OrderByIF(orderByExpression != null, orderByExpression, isAsc ? OrderByType.Asc : OrderByType.Desc)
.WhereIF(whereExpression != null, whereExpression).ToListAsync();
}
public async Task<List<TEntity>> Query(Expression<Func<TEntity, bool>> whereExpression, string orderByFields)
{
return await _db.Queryable<TEntity>().WhereIF(whereExpression != null, whereExpression)
.OrderByIF(orderByFields != null, orderByFields).ToListAsync();
}
public async Task<List<TEntity>> Query(string where, string orderByFields)
{
return await _db.Queryable<TEntity>().OrderByIF(!string.IsNullOrEmpty(orderByFields), orderByFields)
.WhereIF(!string.IsNullOrEmpty(where), where).ToListAsync();
}
public async Task<List<TEntity>> QueryTop(Expression<Func<TEntity, bool>> whereExpression, int top, string orderByFields)
{
return await _db.Queryable<TEntity>()
.OrderByIF(!string.IsNullOrEmpty(orderByFields), orderByFields)
.WhereIF(whereExpression != null, whereExpression)
.Take(top)
.ToListAsync();
}
public async Task<List<TEntity>> QueryTop(string where, int top, string orderByFields)
{
return await _db.Queryable<TEntity>()
.OrderByIF(!string.IsNullOrEmpty(orderByFields), orderByFields)
.WhereIF(!string.IsNullOrEmpty(where), where)
.Take(top)
.ToListAsync();
}
public async Task<List<TEntity>> QueryPage(Expression<Func<TEntity, bool>> whereExpression, int pageIndex, int pageSize, string orderByFields)
{
return await _db.Queryable<TEntity>()
.OrderByIF(!string.IsNullOrEmpty(orderByFields), orderByFields)
.WhereIF(whereExpression != null, whereExpression)
.ToPageListAsync(pageIndex, pageSize);
}
public async Task<List<TEntity>> QueryPage(string where, int pageIndex, int pageSize, string orderByFields)
{
return await _db.Queryable<TEntity>()
.OrderByIF(!string.IsNullOrEmpty(orderByFields), orderByFields)
.WhereIF(!string.IsNullOrEmpty(where), where)
.ToPageListAsync(pageIndex, pageSize);
}
public async Task<PageModel<TEntity>> QueryPageModel(Expression<Func<TEntity, bool>> whereExpression, int pageIndex = 1, int pageSize = 20, Expression<Func<TEntity, object>> orderByExpression = null, bool isAsc = true)
{
RefAsync<int> totalCount = 0;
List<TEntity> list = await _db.Queryable<TEntity>()
.OrderByIF(orderByExpression is not null, orderByExpression, isAsc ? OrderByType.Asc : OrderByType.Desc)
.WhereIF(whereExpression != null, whereExpression)
.ToPageListAsync(pageIndex, pageSize, totalCount);
return new PageModel<TEntity>(pageIndex, totalCount, pageSize, list);
}
public async Task<PageModel<TEntity>> QueryPageModel(Expression<Func<TEntity, bool>> whereExpression, int pageIndex = 1, int pageSize = 20, string orderByFields = null)
{
RefAsync<int> totalCount = 0;
var list = await _db.Queryable<TEntity>()
.OrderByIF(!string.IsNullOrEmpty(orderByFields), orderByFields)
.WhereIF(whereExpression != null, whereExpression)
.ToPageListAsync(pageIndex, pageSize, totalCount);
return new PageModel<TEntity>(pageIndex, totalCount, pageSize, list);
}
public async Task<List<TResult>> QueryDto<TResult>(Expression<Func<TEntity, TResult>> expression)
{
return await _db.Queryable<TEntity>().Select(expression).ToListAsync();
}
public async Task<List<TResult>> QueryDto<TResult>(Expression<Func<TEntity, TResult>> expression, Expression<Func<TEntity, bool>> whereExpression, string orderByFields)
{
return await _db.Queryable<TEntity>()
.OrderByIF(!string.IsNullOrEmpty(orderByFields), orderByFields)
.WhereIF(whereExpression != null, whereExpression)
.Select(expression)
.ToListAsync();
}
public async Task<List<TEntity>> QuerySql(string sql, SugarParameter[] parameters = null)
{
return await _db.Ado.SqlQueryAsync<TEntity>(sql, parameters);
}
public async Task<DataTable> QueryTable(string sql, SugarParameter[] parameters = null)
{
return await _db.Ado.GetDataTableAsync(sql, parameters);
}
/// <summary>
/// 两表联查
/// </summary>
public async Task<List<TResult>> QueryMuch<T, T2, TResult>(Expression<Func<T, T2, object[]>> joinExpression,
Expression<Func<T, T2, bool>> whereExpression,
Expression<Func<T, T2, TResult>> selectExpression) where T : class, new()
{
return await _db.Queryable(joinExpression)
.WhereIF(whereExpression != null, whereExpression)
.Select(selectExpression)
.ToListAsync();
}
/// <summary>
/// 两表联合查询-分页
/// </summary>
public async Task<PageModel<TResult>> QueryMuchPage<T, T2, TResult>(Expression<Func<T, T2, object[]>> joinExpression,
Expression<Func<T, T2, bool>> whereExpression,
Expression<Func<T, T2, TResult>> selectExpression,
int pageIndex = 1,
int pageSize = 20,
string strOrderByFileds = null)
{
RefAsync<int> totalCount = 0;
List<TResult> list = await _db.Queryable<T, T2>(joinExpression)
.WhereIF(whereExpression != null, whereExpression)
.OrderByIF(!string.IsNullOrEmpty(strOrderByFileds), strOrderByFileds)
.Select(selectExpression)
.ToPageListAsync(pageIndex, pageSize, totalCount);
return new PageModel<TResult>(pageIndex, totalCount, pageSize, list);
}
/// <summary>
/// 两表联合查询-分页-分组
/// </summary>
public async Task<PageModel<TResult>> QueryMuchPageGroup<T, T2, TResult>(Expression<Func<T, T2, object[]>> joinExpression,
Expression<Func<T, T2, bool>> whereExpression,
Expression<Func<T, T2, TResult>> selectExpression,
Expression<Func<T, object>> groupExpression,
int pageIndex = 1,
int pageSize = 20,
string strOrderByFileds = null)
{
RefAsync<int> totalCount = 0;
List<TResult> list = await _db.Queryable<T, T2>(joinExpression)
.WhereIF(whereExpression != null, whereExpression)
.GroupBy(groupExpression)
.OrderByIF(!string.IsNullOrEmpty(strOrderByFileds), strOrderByFileds)
.Select(selectExpression)
.ToPageListAsync(pageIndex, pageSize, totalCount);
return new PageModel<TResult>(pageIndex, totalCount, pageSize, list);
}
/// <summary>
/// 三表联查
/// </summary>
public async Task<List<TResult>> QueryMuch<T, T2, T3, TResult>(
Expression<Func<T, T2, T3, object[]>> joinExpression,
Expression<Func<T, T2, T3, bool>> whereLambda,
Expression<Func<T, T2, T3, TResult>> 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();
}
/// <summary>
/// 三表联合查询-分页
/// </summary>
public async Task<PageModel<TResult>> QueryMuchPage<T, T2, T3, TResult>(Expression<Func<T, T2, T3, object[]>> joinExpression,
Expression<Func<T, T2, T3, bool>> whereExpression,
Expression<Func<T, T2, T3, TResult>> selectExpression,
int pageIndex = 1,
int pageSize = 20,
string strOrderByFileds = null)
{
RefAsync<int> totalCount = 0;
List<TResult> list = await _db.Queryable<T, T2, T3>(joinExpression)
.WhereIF(whereExpression != null, whereExpression)
.OrderByIF(!string.IsNullOrEmpty(strOrderByFileds), strOrderByFileds)
.Select(selectExpression)
.ToPageListAsync(pageIndex, pageSize, totalCount).ConfigureAwait(false);
return new PageModel<TResult>(pageIndex, totalCount, pageSize, list);
}
#endregion
#region 新增
public async Task<long> Add(TEntity entity)
{
var insert = _db.Insertable(entity);
return await insert.ExecuteReturnSnowflakeIdAsync();
//这里你可以返回TEntity这样的话就可以获取id值无论主键是什么类型
//var return3 = await insert.ExecuteReturnEntityAsync();
}
public async Task<List<long>> Add(List<TEntity> listEntity)
{
return await _db.Insertable(listEntity.ToArray()).ExecuteReturnSnowflakeIdListAsync();
}
#endregion
#region 删除
public async Task<bool> Delete(Expression<Func<TEntity, bool>> whereExpression)
{
return await _db.Deleteable(whereExpression).ExecuteCommandHasChangeAsync();
}
public async Task<bool> Delete(TEntity entity)
{
return await _db.Deleteable(entity).ExecuteCommandHasChangeAsync();
}
public async Task<bool> DeleteById(object id)
{
return await _db.Deleteable<TEntity>().In(id).ExecuteCommandHasChangeAsync();
}
public async Task<bool> DeleteByIds(object[] ids)
{
return await _db.Deleteable<TEntity>().In(ids).ExecuteCommandHasChangeAsync();
}
#endregion
#region 更新
public async Task<bool> Update(TEntity entity)
{
////这种方式会以主键为条件
//var i = await Task.Run(() => _db.Updateable(entity).ExecuteCommand());
//return i > 0;
//这种方式会以主键为条件
return await _db.Updateable(entity).ExecuteCommandHasChangeAsync();
}
public async Task<bool> Update(TEntity entity, Expression<Func<TEntity, object>> updateColumns)
{
return await _db.Updateable(entity).UpdateColumns(updateColumns, true).ExecuteCommandHasChangeAsync();
}
public async Task<bool> Update(List<TEntity> entity)
{
return await _db.Updateable(entity).ExecuteCommandHasChangeAsync();
}
public async Task<bool> Update(TEntity entity, string where)
{
return await _db.Updateable(entity).Where(where).ExecuteCommandHasChangeAsync();
}
public async Task<bool> Update(object operateAnonymousObjects)
{
return await _db.Updateable<TEntity>(operateAnonymousObjects).ExecuteCommandAsync() > 0;
}
public async Task<bool> Update(TEntity entity, List<string> lstColumns = null, List<string> lstIgnoreColumns = null, string where = "")
{
IUpdateable<TEntity> 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(), true);
}
if (!string.IsNullOrEmpty(where))
{
up = up.Where(where);
}
return await up.ExecuteCommandHasChangeAsync();
}
public async Task<bool> Update(Expression<Func<TEntity, TEntity>> columns, Expression<Func<TEntity, bool>> where)
{
return await _db.Updateable<TEntity>()
.SetColumns(columns)
.Where(where)
.ExecuteCommandHasChangeAsync();
}
#endregion
#region Split分表基础接口 基础CRUD
/// <summary>
/// 分页查询
/// </summary>
public async Task<PageModel<TEntity>> QueryPageSplit(Expression<Func<TEntity, bool>> whereExpression, DateTime beginTime, DateTime endTime, int pageIndex = 1, int pageSize = 20, string orderByFields = null)
{
RefAsync<int> totalCount = 0;
var list = await _db.Queryable<TEntity>().SplitTable(beginTime, endTime)
.OrderByIF(!string.IsNullOrEmpty(orderByFields), orderByFields)
.WhereIF(whereExpression != null, whereExpression)
.ToPageListAsync(pageIndex, pageSize, totalCount);
var data = new PageModel<TEntity>(pageIndex, totalCount, pageSize, list);
return data;
}
/// <summary>
/// 写入实体数据
/// </summary>
public async Task<List<long>> AddSplit(TEntity entity)
{
var insert = _db.Insertable(entity).SplitTable();
//插入并返回雪花ID并且自动赋值ID 
return await insert.ExecuteReturnSnowflakeIdListAsync();
}
/// <summary>
/// 更新实体数据
/// </summary>
public async Task<bool> UpdateSplit(TEntity entity, DateTime dateTime)
{
//直接根据实体集合更新 (全自动 找表更新)
//return await _db.Updateable(entity).SplitTable().ExecuteCommandAsync();//,SplitTable不能少
//精准找单个表
var tableName = _db.SplitHelper<TEntity>().GetTableName(dateTime); //根据时间获取表名
return await _db.Updateable(entity).AS(tableName).ExecuteCommandHasChangeAsync();
}
/// <summary>
/// 删除数据
/// </summary>
/// <param name="entity"></param>
/// <param name="dateTime"></param>
/// <returns></returns>
public async Task<bool> DeleteSplit(TEntity entity, DateTime dateTime)
{
////直接根据实体集合删除 (全自动 找表插入),返回受影响数
//return await _db.Deleteable(entity).SplitTable().ExecuteCommandAsync();//,SplitTable不能少
//精准找单个表
var tableName = _db.SplitHelper<TEntity>().GetTableName(dateTime); //根据时间获取表名
return await _db.Deleteable<TEntity>().AS(tableName).Where(entity).ExecuteCommandHasChangeAsync();
}
/// <summary>
/// 根据ID查找数据
/// </summary>
/// <param name="objId"></param>
/// <returns></returns>
public async Task<TEntity> QueryByIdSplit(object objId)
{
return await _db.Queryable<TEntity>().In(objId).SplitTable(tabs => tabs).SingleAsync();
}
#endregion
}
}