using SqlSugar; using System.Linq.Expressions; using UIStandardWebApi.Entity; using UIStandardWebApi.IService; namespace UIStandardWebApi.Service { public abstract class BaseService : IBaseService { /// /// /// protected ISqlSugarClient _Client { get; set; } /// /// 构造函数 /// /// public BaseService(ISqlSugarClient client) { _Client = client; } #region Query /// /// 主键查询 /// /// /// /// public T Find(int id) where T : class { return _Client.Queryable().InSingle(id); } /// /// 主键查询-异步版本 /// /// /// /// public async Task FindAsync(int id) where T : class { return await _Client.Queryable().InSingleAsync(id); } /// /// 不应该暴露给上端使用者,尽量少用 /// /// /// [Obsolete("尽量避免使用,using 带表达式目录树的代替")] public ISugarQueryable Set() where T : class { return _Client.Queryable(); } /// /// 条件查询 /// /// /// /// public ISugarQueryable Query(Expression> funcWhere) where T : class { return _Client.Queryable().Where(funcWhere); } /// /// 分页查询 /// /// /// /// /// /// /// /// public PagingData QueryPage(Expression> funcWhere, int pageSize, int pageIndex, Expression> funcOrderby, bool isAsc = true) where T : class { var list = _Client.Queryable(); if (funcWhere != null) { list = list.Where(funcWhere); } list = list.OrderByIF(true, funcOrderby, isAsc ? OrderByType.Asc : OrderByType.Desc); PagingData result = new PagingData() { DataList = list.ToPageList(pageIndex, pageSize), PageIndex = pageIndex, PageSize = pageSize, RecordCount = list.Count(), }; return result; } #endregion #region Insert /// /// 新增数据-同步版本 /// /// /// /// public T Insert(T t) where T : class, new() { return _Client.Insertable(t).ExecuteReturnEntity(); } /// /// 新增数据-异步版本 /// /// /// /// public async Task InsertAsync(T t) where T : class, new() { return await _Client.Insertable(t).ExecuteReturnEntityAsync(); } /// /// 批量新增-事务执行 /// /// /// /// public async Task InsertList(List tList) where T : class, new() { return await _Client.Insertable(tList.ToList()).ExecuteCommandIdentityIntoEntityAsync(); } #endregion #region Update /// /// 是没有实现查询,直接更新的,需要Attach和State /// /// 如果是已经在context,只能再封装一个(在具体的service) /// /// /// public async Task UpdateAsync(T t) where T : class, new() { if (t == null) throw new Exception("t is null"); return await _Client.Updateable(t).ExecuteCommandHasChangeAsync(); } public void Update(List tList) where T : class, new() { _Client.Updateable(tList).ExecuteCommand(); } #endregion #region Delete /// /// 先附加 再删除 /// /// /// public void Delete(T t) where T : class, new() { _Client.Deleteable(t).ExecuteCommand(); } /// /// 根据主键删除 /// /// /// /// public bool Delete(object pId) where T : class, new() { T t = _Client.Queryable().InSingle(pId); return _Client.Deleteable(t).ExecuteCommand() > 0; } public void Delete(List tList) where T : class { _Client.Deleteable(tList).ExecuteCommand(); } #endregion #region Other ISugarQueryable IBaseService.ExcuteQuery(string sql) where T : class { return _Client.SqlQueryable(sql); } public void Dispose() { if (_Client != null) { _Client.Dispose(); } } #endregion } }