using SqlSugar;
using System.Linq.Expressions;
namespace dy.net.repository
{
///
/// 通用Repository基类
///
/// 实体类型
public abstract class BaseRepository where T : class, new()
{
///
/// SQLSugar客户端
///
protected readonly ISqlSugarClient Db;
///
/// 构造函数注入SQLSugar客户端
///
/// SQLSugar客户端实例
protected BaseRepository(ISqlSugarClient db)
{
Db = db;
}
#region 新增操作
///
/// 新增单个实体
///
/// 实体对象
/// 是否新增成功
public virtual bool Insert(T entity)
{
return Db.Insertable(entity).ExecuteCommand() > 0;
}
///
/// 新增单个实体(异步)
///
/// 实体对象
/// 是否新增成功
public virtual async Task InsertAsync(T entity)
{
return await Db.Insertable(entity).ExecuteCommandAsync() > 0;
}
///
/// 批量新增实体
///
/// 实体集合
/// 新增的数量
public virtual int InsertRange(IEnumerable entities)
{
return Db.Insertable(entities.ToArray()).ExecuteCommand();
}
///
/// 批量新增实体(异步)
///
/// 实体集合
/// 新增的数量
public virtual async Task InsertRangeAsync(IEnumerable entities)
{
return await Db.Insertable(entities.ToArray()).ExecuteCommandAsync();
}
///
/// 新增实体并返回自增ID
///
/// 实体对象
/// 自增ID
public virtual int InsertReturnIdentity(T entity)
{
return Db.Insertable(entity).ExecuteReturnIdentity();
}
///
/// 新增实体并返回自增ID(异步)
///
/// 实体对象
/// 自增ID
public virtual async Task InsertReturnIdentityAsync(T entity)
{
return await Db.Insertable(entity).ExecuteReturnIdentityAsync();
}
#endregion
#region 删除操作
///
/// 根据主键删除
///
/// 主键值
/// 是否删除成功
public virtual bool DeleteById(object id)
{
return Db.Deleteable().In(id).ExecuteCommand() > 0;
}
///
/// 事务执行
///
///
///
///
public async Task UseTranAsync(Func action, Action errorCallBack)
{
var res = await Db.Ado.UseTranAsync(async () =>
{
await action();
}, errorCallBack: errorCallBack);
return res.IsSuccess;
}
///
/// 根据主键删除(异步)
///
/// 主键值
/// 是否删除成功
public virtual async Task DeleteByIdAsync(object id)
{
return await Db.Deleteable().In(id).ExecuteCommandAsync() > 0;
}
///
/// 根据主键集合删除
///
/// 主键集合
/// 删除的数量
public virtual int DeleteByIds(IEnumerable