using SqlSugar;
using System.Linq.Expressions;
using Txgy.RBS.Framework;
using Txgy.RBS.IServices;
namespace Txgy.RBS.Services
{
public 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);
}
///
/// 不应该暴露给上端使用者,尽量少用
///
///
///
[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
///
/// 即使保存 不需要再Commit
///
///
///
///
public T Insert(T t) where T : class, new()
{
_Client.Insertable(t).ExecuteCommand();
return t;
}
public IEnumerable Insert(List tList) where T : class, new()
{
_Client.Insertable(tList.ToList()).ExecuteCommand();
return tList;
}
#endregion
#region Update
///
/// 是没有实现查询,直接更新的,需要Attach和State
///
/// 如果是已经在context,只能再封装一个(在具体的service)
///
///
///
public void Update(T t) where T : class, new()
{
if (t == null) throw new Exception("t is null");
_Client.Updateable(t).ExecuteCommand();
}
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();
}
///
/// 还可以增加非即时commit版本的,
/// 做成protected
///
///
///
public void Delete(int Id) where T : class, new()
{
T t = _Client.Queryable().InSingle(Id);
_Client.Deleteable(t).ExecuteCommand();
}
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
}
}