using SqlSugar; namespace DBHelper { /// /// DB,禁止跨上下文使用 /// 1.异步情况: 在同一串await 中是一个上下文 (await 会改变线程和同步是不一样的) /// 2.同步情况: 在同一个线程是同一个上下文 /// public class Db { /// /// 上下文集合 /// private static readonly List _contexts = new List(); /// /// 默认上下文类类型 /// public static string DefaultDbContextType { get; private set; } = null!; /// /// 指定连接连接 /// /// 业务代码 /// 业务逻辑 /// 连接对应的Key /// /// public static T Do(Func func, string key) { var db = new Db(); db.Context(key).BeginTran(); var res = func(db); db.Context(key).CommitTran(); return res; } /// /// 使用设置好的默认链接 /// /// 执行内容 public static void Do(Action act) { Do(db => { act(db); return 1; }, DefaultDbContextType); } /// /// 使用指定默认链接 /// /// 执行内容 /// 连接对应的Key public static void Do(Action act, string key) { Do(db => { act(db); return 1; }, key); } /// /// 设置默认链接 /// /// public static void SetDefaultDbContextType(string key) { DefaultDbContextType = key; } /// /// 默认链接 /// public SqlSugarScope Default { get { if (DefaultDbContextType == null) throw new Exception("请先设置默认数据库,调用静态方法SetDefaultDbContextType()"); return Context(DefaultDbContextType); } } /// /// 创建一个数据库连接 /// /// 数据库配置信息 /// 数据库Key /// public static SqlSugarScope CreateContext(ConnectionConfig config, string key) { var ctx = _contexts.FirstOrDefault(v => v.Key == key); if (ctx != null) return ctx.Client; ctx = new ContextList(key, new SqlSugarScope(new ConnectionConfig() { ConnectionString = config.ConnectionString, DbType = config.DbType, IsAutoCloseConnection = true }), config); _contexts.Add(ctx); return ctx.Client; } /// /// 根据Key获取指定数据库连接 /// /// 目标数据库在配置中的Key /// /// public SqlSugarScope Context(string key) { var ctx = _contexts.FirstOrDefault(v => v.Key == key); if (ctx == null) throw new Exception("没有对应的链接,请先调用创建"); return ctx.Client; } } /// /// 链接 /// public class ContextList { /// /// /// /// /// /// public ContextList(string key, SqlSugarScope client, ConnectionConfig connectionConfig) { Key = key; Client = client; ConnectionConfig = connectionConfig; } /// /// /// public string Key { get; set; } /// /// /// public SqlSugarScope Client { get; set; } /// /// /// public ConnectionConfig ConnectionConfig { get; set; } } }