using DbType = SqlSugar.DbType;
namespace Admin.NET.Core;
public static class SqlSugarSetup
{
///
/// Sqlsugar上下文初始化
///
///
///
public static void AddSqlSugarSetup(this IServiceCollection services, IConfiguration configuration)
{
// SqlSugarScope用AddSingleton单例
services.AddSingleton(provider =>
{
var dbOptions = App.GetOptions();
DealConnectionStr(ref dbOptions); // 处理本地库根目录路径
var connectionConfigs = SqlSugarConst.ConnectionConfigs; // 方便多库生成
var configureExternalServices = new ConfigureExternalServices
{
EntityService = (type, column) => // 修改列可空
{
// 1、带?问号 2、String类型若没有Required
if ((type.PropertyType.IsGenericType && type.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
|| (type.PropertyType == typeof(string) && type.GetCustomAttribute() == null))
column.IsNullable = true;
},
};
var defaultConnection = new ConnectionConfig()
{
DbType = (DbType)Convert.ToInt32(Enum.Parse(typeof(DbType), dbOptions.DefaultDbType)),
ConnectionString = dbOptions.DefaultConnection,
IsAutoCloseConnection = true,
ConfigId = dbOptions.DefaultConfigId,
ConfigureExternalServices = configureExternalServices
};
connectionConfigs.Add(defaultConnection);
dbOptions.DbConfigs.ForEach(config =>
{
var connection = new ConnectionConfig()
{
DbType = (DbType)Convert.ToInt32(Enum.Parse(typeof(DbType), config.DbType)),
ConnectionString = config.DbConnection,
IsAutoCloseConnection = true,
ConfigId = config.DbConfigId,
ConfigureExternalServices = configureExternalServices
};
connectionConfigs.Add(connection);
});
SqlSugarScope sqlSugar = new(connectionConfigs, db =>
{
connectionConfigs.ForEach(config =>
{
var dbProvider = db.GetConnection((string)config.ConfigId);
// 设置超时时间
dbProvider.Ado.CommandTimeOut = 30;
// 打印SQL语句
dbProvider.Aop.OnLogExecuting = (sql, pars) =>
{
if (sql.StartsWith("SELECT"))
Console.ForegroundColor = ConsoleColor.Green;
if (sql.StartsWith("UPDATE") || sql.StartsWith("INSERT"))
Console.ForegroundColor = ConsoleColor.White;
if (sql.StartsWith("DELETE"))
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine("\r\n" + "=========执行SQL============" + "\r\n" + UtilMethods.GetSqlString(DbType.MySql, sql, pars) + "\r\n");
//Console.WriteLine(sql + "\r\n" + db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)) + "\r\n" + "========================" + "\r\n");
App.PrintToMiniProfiler("SqlSugar", "Info", sql + "\r\n" + db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
};
dbProvider.Aop.OnError = (ex) =>
{
Console.ForegroundColor = ConsoleColor.Red;
var pars = db.Utilities.SerializeObject(((SugarParameter[])ex.Parametres).ToDictionary(it => it.ParameterName, it => it.Value));
Console.WriteLine("\r\n" + "=========SQL错误============" + "\r\n" + UtilMethods.GetSqlString(DbType.MySql, ex.Sql, (SugarParameter[])ex.Parametres) + "\r\n");
//Console.WriteLine($"{ex.Message}{Environment.NewLine}{ex.Sql}{Environment.NewLine}{pars}{Environment.NewLine}");
App.PrintToMiniProfiler("SqlSugar", "Error", $"{ex.Message}{Environment.NewLine}{ex.Sql}{pars}{Environment.NewLine}");
};
// 数据审计
dbProvider.Aop.DataExecuting = (oldValue, entityInfo) =>
{
// 新增操作
if (entityInfo.OperationType == DataFilterType.InsertByObject)
{
// 主键(long)-赋值雪花Id
if (entityInfo.EntityColumnInfo.IsPrimarykey && entityInfo.EntityColumnInfo.PropertyInfo.PropertyType == typeof(long))
entityInfo.SetValue(Yitter.IdGenerator.YitIdHelper.NextId());
if (entityInfo.PropertyName == "CreateTime")
entityInfo.SetValue(DateTime.Now);
if (App.User != null)
{
if (entityInfo.PropertyName == "TenantId")
{
var tenantId = ((dynamic)entityInfo.EntityValue).TenantId;
if (tenantId == null || tenantId == 0)
entityInfo.SetValue(App.User.FindFirst(ClaimConst.TenantId)?.Value);
}
if (entityInfo.PropertyName == "CreateUserId")
entityInfo.SetValue(App.User.FindFirst(ClaimConst.UserId)?.Value);
if (entityInfo.PropertyName == "CreateOrgId")
entityInfo.SetValue(App.User.FindFirst(ClaimConst.OrgId)?.Value);
}
}
// 更新操作
if (entityInfo.OperationType == DataFilterType.UpdateByObject)
{
if (entityInfo.PropertyName == "UpdateTime")
entityInfo.SetValue(DateTime.Now);
if (entityInfo.PropertyName == "UpdateUserId")
entityInfo.SetValue(App.User?.FindFirst(ClaimConst.UserId)?.Value);
}
};
// 差异日志
dbProvider.Aop.OnDiffLogEvent = async u =>
{
if (!dbOptions.EnableDiffLog) return;
var LogDiff = new SysLogDiff
{
// 操作后记录(字段描述、列名、值、表名、表描述)
AfterData = Newtonsoft.Json.JsonConvert.SerializeObject(u.AfterData),
// 操作前记录(字段描述、列名、值、表名、表描述)
BeforeData = Newtonsoft.Json.JsonConvert.SerializeObject(u.BeforeData),
// 传进来的对象
BusinessData = Newtonsoft.Json.JsonConvert.SerializeObject(u.BusinessData),
// enum(insert、update、delete)
DiffType = u.DiffType.ToString(),
Sql = UtilMethods.GetSqlString(DbType.MySql, u.Sql, u.Parameters),
Parameters = Newtonsoft.Json.JsonConvert.SerializeObject(u.Parameters),
Duration = u.Time == null ? 0 : (long)u.Time.Value.TotalMilliseconds
};
await dbProvider.Insertable(LogDiff).ExecuteCommandAsync();
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"***差异日志开始***{ Environment.NewLine }{ Newtonsoft.Json.JsonConvert.SerializeObject(LogDiff) }{ Environment.NewLine }***差异日志结束***");
};
// 配置实体假删除过滤器
SetDeletedEntityFilter(dbProvider);
// 配置实体机构过滤器
SetOrgEntityFilter(dbProvider);
// 配置自定义实体过滤器
SetCustomEntityFilter(dbProvider);
// 配置租户实体过滤器
SetTenantEntityFilter(dbProvider);
});
});
// 初始化数据库结构及种子数据
if (dbOptions.EnableInitTable)
InitDataBase(sqlSugar, dbOptions);
return sqlSugar;
});
services.AddScoped(typeof(SqlSugarRepository<>)); // 注册仓储
}
///
/// 初始化数据库结构
///
public static void InitDataBase(SqlSugarScope db, ConnectionStringsOptions dbOptions)
{
// 创建默认数据库
db.DbMaintenance.CreateDatabase();
// 创建业务数据库
dbOptions.DbConfigs.ForEach(config =>
{
db.GetConnection(config.DbConfigId).DbMaintenance.CreateDatabase();
});
// 获取所有实体表
var entityTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
&& u.IsDefined(typeof(SqlSugarEntityAttribute), false))
.OrderByDescending(u => u.GetSqlSugarEntityOrder());
if (!entityTypes.Any()) return;
// 初始化库表结构
foreach (var entityType in entityTypes)
{
var dbConfigId = entityType.GetCustomAttribute(true).DbConfigId;
db.ChangeDatabase(dbConfigId);
db.CodeFirst.InitTables(entityType);
}
// 获取所有实体种子数据
var seedDataTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
&& u.GetInterfaces().Any(i => i.HasImplementedRawGeneric(typeof(ISqlSugarEntitySeedData<>))));
if (!seedDataTypes.Any()) return;
foreach (var seedType in seedDataTypes)
{
var instance = Activator.CreateInstance(seedType);
var hasDataMethod = seedType.GetMethod("HasData");
var seedData = ((IList)hasDataMethod?.Invoke(instance, null))?.Cast