using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
namespace DBHelper_SqlSugar
{
///
/// DB,禁止跨上下文使用
/// 1.异步情况: 在同一串await 中是一个上下文 (await 会改变线程和同步是不一样的)
/// 2.同步情况: 在同一个线程是同一个上下文
///
public class Db
{
///
/// 上下文集合
///
private static List _contexts = new List();
///
/// 默认上下文类类型
///
public static string DefaultDbContextType { get; private set; } = null!;
public static T Do(Func func)
{
var db = new Db();
try
{
db.Default.BeginTran();
var res = func(db);
db.Default.CommitTran();
return res;
}
catch (Exception ex)
{
//var qty = ex.EntityValidationErrors.Count();
//var info = ex.EntityValidationErrors.First();
//var msg = "有" + qty + "条数据验证失败,首条错误信息:\n" + string.Join("\n", info.MemberNames) + "\n" + (info.ErrorMessage ?? "");
Console.WriteLine(ex.Message);
throw new Exception(ex.Message);
}
}
public static void Do(Action act)
{
Do(db =>
{
act(db);
return 1;
});
}
///
/// 设置默认链接
///
///
public static void SetDefaultDbContextType(string key)
{
DefaultDbContextType = key;
}
///
/// 默认链接
///
public SqlSugarScope Default
{
get
{
if (DefaultDbContextType == null)
throw new Exception("请先设置默认数据库,调用静态方法SetDefaultDbContextType()");
return Context(DefaultDbContextType);
}
}
///
/// 创建一个上下文
///
///
///
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;
}
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)
{
this.Key = key;
Client = client;
ConnectionConfig = connectionConfig;
}
public string Key { get; set; }
public SqlSugarScope Client { get; set; }
public ConnectionConfig ConnectionConfig { get; set; }
}
}