using SqlSugar; using SqlSugar.IOC; using System; using System.Collections.Generic; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace RIZO_Application.Repository { public class BaseRepository : SimpleClient where T : class, new() { private readonly ISqlSugarClient Context; public BaseRepository(ISqlSugarClient context = null) : base(context) { var configId = typeof(T).GetCustomAttribute()?.configId; if (configId != null) { // 在 同一个上下文 或者 同一个异步上下文 SqlSugar是同一个对象 // SqlSugarScope 的实例不是线程安全的。这意味着每个线程应该有自己的 SqlSugarScope 实例 Context = DbScoped.SugarScope.GetConnectionScope(configId);//根据类传入的ConfigId自动选择 // db.CopyNew() 用于在多线程或多任务环境中创建新的 SqlSugarClient 或 SqlSugarScope 实例,以确保线程安全和资源管理。 } else { Context = context ?? DbScoped.SugarScope.GetConnectionScope(0);//没有默认db0 } } public async Task GetByIdAsync(object id) { return await Context.Queryable().InSingleAsync(id); } public async Task> GetAllAsync() { return await Context.Queryable().ToListAsync(); } public async Task InsertAsync(T entity) { return await Context.Insertable(entity).ExecuteCommandAsync() > 0; } public async Task UpdateAsync(T entity) { return await Context.Updateable(entity).ExecuteCommandAsync() > 0; } public async Task DeleteAsync(T entity) { return await Context.Deleteable(entity).ExecuteCommandAsync() > 0; } public async Task DeleteByIdAsync(object id) { return await Context.Deleteable().In(id).ExecuteCommandAsync() > 0; } } }