LFlow/LFlow.Base/Default/DefaultCurdRepo.cs

93 lines
2.5 KiB
C#
Raw Normal View History

2024-10-16 11:27:57 +08:00
using LFlow.Base.Interfaces;
using LFlow.Base.Utils;
2024-10-16 11:27:57 +08:00
using SqlSugar;
namespace LFlow.Base.Default;
/// <summary>
/// 默认的增删改查仓储
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="K"></typeparam>
2024-10-16 11:27:57 +08:00
public abstract class DefaultCurdRepo<T, K> : IRepo<T, K> where T : class, IDataModel, new()
{
private readonly ISqlSugarClient _client;
public DefaultCurdRepo(ISqlSugarClient client)
{
_client = client;
}
/// <summary>
/// 根据ID删除对象
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
public virtual int DeleteById(K id)
2024-10-16 11:27:57 +08:00
{
if (Get(id) != null)
{
return _client.Deleteable<T>().In(id).ExecuteCommand();
}
else
{
throw new Exception("删除的对象不存在");
}
}
/// <summary>
/// 根据ID获取对象
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
2024-10-16 11:27:57 +08:00
public virtual T Get(K id)
{
return _client.Queryable<T>().InSingle(id);
}
/// <summary>
/// 批量查询(分页)
/// </summary>
/// <param name="pageIndex"></param>
/// <param name="pageSize"></param>
/// <param name="pageTotal"></param>
/// <returns></returns>
2024-10-16 11:27:57 +08:00
public List<T> GetAll(int pageIndex, int pageSize, ref int pageTotal)
{
return _client.Queryable<T>().ToPageList(pageIndex, pageSize, ref pageTotal);
}
/// <summary>
/// 报错或是更新对象
/// </summary>
/// <param name="entity"></param>
/// <param name="isUpdate"></param>
/// <returns></returns>
2024-10-16 11:27:57 +08:00
public virtual T SaveOrUpdate(T entity, bool isUpdate)
{
if (isUpdate)
{
_client.Updateable(entity).ExecuteCommand();
}
else
{
_client.Insertable(entity).ExecuteCommand();
}
return entity;
}
/// <summary>
/// 搜索
/// </summary>
/// <param name="whereObj"></param>
/// <returns></returns>
public virtual List<T> Search(T whereObj)
{
return _client.Queryable<T>().Where(whereObj.ToWhereExp()).ToList();
}
/// <summary>
/// 查找ID
/// </summary>
/// <param name="whereObj"></param>
/// <returns></returns>
public virtual List<K> WhereSearchId(T whereObj)
{
return _client.Queryable<T>().Where(whereObj.ToWhereExp()).Select(x => (K)Convert.ChangeType(x.ID, typeof(K))).ToList();
}
2024-10-16 11:27:57 +08:00
}