Files
shgxtzcjhoudaosaomadayinwpf/RIZO_Application.Repository/BaseRepository.cs

62 lines
2.2 KiB
C#

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<T> : SimpleClient<T> where T : class, new()
{
private readonly ISqlSugarClient Context;
public BaseRepository(ISqlSugarClient context = null) : base(context)
{
var configId = typeof(T).GetCustomAttribute<TenantAttribute>()?.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<T> GetByIdAsync(object id)
{
return await Context.Queryable<T>().InSingleAsync(id);
}
public async Task<List<T>> GetAllAsync()
{
return await Context.Queryable<T>().ToListAsync();
}
public async Task<bool> InsertAsync(T entity)
{
return await Context.Insertable(entity).ExecuteCommandAsync() > 0;
}
public async Task<bool> UpdateAsync(T entity)
{
return await Context.Updateable(entity).ExecuteCommandAsync() > 0;
}
public async Task<bool> DeleteAsync(T entity)
{
return await Context.Deleteable(entity).ExecuteCommandAsync() > 0;
}
public async Task<bool> DeleteByIdAsync(object id)
{
return await Context.Deleteable<T>().In(id).ExecuteCommandAsync() > 0;
}
}
}