namespace Cis.Core; public static class SqlSugarSetup { /// /// Sqlsugar 上下文初始化 /// /// public static void AddSqlSugar(this IServiceCollection services) { var dbOptions = App.GetOptions(); 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; }, DataInfoCacheService = new SqlSugarCache(), }; dbOptions.ConnectionConfigs.ForEach(config => { config.ConfigureExternalServices = configureExternalServices; config.InitKeyType = InitKeyType.Attribute; config.IsAutoCloseConnection = true; config.MoreSettings = new ConnMoreSettings { IsAutoRemoveDataCache = true }; }); SqlSugarScope sqlSugar = new(dbOptions.ConnectionConfigs.Adapt>(), client => { dbOptions.ConnectionConfigs.ForEach(config => { var db = client.GetConnectionScope((string)config.ConfigId); // 设置超时时间 db.Ado.CommandTimeOut = 30; // 打印SQL语句 db.Aop.OnLogExecuting = (sql, pars) => { if (sql.StartsWith("SELECT", StringComparison.OrdinalIgnoreCase)) Console.ForegroundColor = ConsoleColor.Green; if (sql.StartsWith("UPDATE", StringComparison.OrdinalIgnoreCase) || sql.StartsWith("INSERT", StringComparison.OrdinalIgnoreCase)) Console.ForegroundColor = ConsoleColor.White; if (sql.StartsWith("DELETE", StringComparison.OrdinalIgnoreCase)) Console.ForegroundColor = ConsoleColor.Blue; Console.WriteLine("【" + DateTime.Now + "——执行SQL】\r\n" + UtilMethods.GetSqlString(config.DbType, sql, pars) + "\r\n"); App.PrintToMiniProfiler("SqlSugar", "Info", sql + "\r\n" + db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value))); }; db.Aop.OnError = (ex) => { Console.ForegroundColor = ConsoleColor.Red; var pars = db.Utilities.SerializeObject(((SugarParameter[])ex.Parametres).ToDictionary(it => it.ParameterName, it => it.Value)); Console.WriteLine("【" + DateTime.Now + "——错误SQL】\r\n" + UtilMethods.GetSqlString(config.DbType, ex.Sql, (SugarParameter[])ex.Parametres) + "\r\n"); App.PrintToMiniProfiler("SqlSugar", "Error", $"{ex.Message}{Environment.NewLine}{ex.Sql}{pars}{Environment.NewLine}"); }; // 数据审计 db.Aop.DataExecuting = (oldValue, entityInfo) => { // 新增操作 if (entityInfo.OperationType == DataFilterType.InsertByObject) { // 主键(long类型)且没有值的---赋值雪花Id if (entityInfo.EntityColumnInfo.IsPrimarykey && entityInfo.EntityColumnInfo.PropertyInfo.PropertyType == typeof(long)) { var id = entityInfo.EntityColumnInfo.PropertyInfo.GetValue(entityInfo.EntityValue); if (id == null || (long)id == 0) entityInfo.SetValue(Yitter.IdGenerator.YitIdHelper.NextId()); } if (entityInfo.PropertyName == "CreateTime") entityInfo.SetValue(DateTime.Now); } // 更新操作 if (entityInfo.OperationType == DataFilterType.UpdateByObject) { if (entityInfo.PropertyName == "UpdateTime") entityInfo.SetValue(DateTime.Now); } }; }); }); // 初始化数据库表结构及种子数据 InitDataBase(sqlSugar, dbOptions); services.AddSingleton(sqlSugar); // 单例注册 services.AddScoped(typeof(SqlSugarRepository<>)); // 注册仓储 services.AddUnitOfWork(); // 注册事务与工作单元 } /// /// 初始化数据库结构 /// private static void InitDataBase(SqlSugarScope db, DbConnectionOptions dbOptions) { // 创建数据库 dbOptions.ConnectionConfigs.ForEach(config => { if (!config.EnableInitDb || config.DbType == SqlSugar.DbType.Oracle) return; db.GetConnectionScope(config.ConfigId).DbMaintenance.CreateDatabase(); }); // 获取所有实体表-初始化表结构 var entityTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass && u.IsDefined(typeof(SugarTable), false) && !u.IsDefined(typeof(NotTableAttribute), false)); if (!entityTypes.Any()) return; foreach (var entityType in entityTypes) { var tAtt = entityType.GetCustomAttribute(); // 多数据库 var configId = tAtt == null ? SqlSugarConst.DefaultConfigId : tAtt.configId.ToString(); if (!dbOptions.ConnectionConfigs.FirstOrDefault(u => u.ConfigId == configId).EnableInitDb) continue; var db2 = db.GetConnectionScope(configId); var splitTable = entityType.GetCustomAttribute(); // 分表 if (splitTable == null) db2.CodeFirst.InitTables(entityType); else db2.CodeFirst.SplitTables().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 = ((IEnumerable)hasDataMethod?.Invoke(instance, null))?.Cast(); if (seedData == null) continue; var entityType = seedType.GetInterfaces().First().GetGenericArguments().First(); var tAtt = entityType.GetCustomAttribute(); var configId = tAtt == null ? SqlSugarConst.DefaultConfigId : tAtt.configId.ToString(); if (!dbOptions.ConnectionConfigs.FirstOrDefault(u => u.ConfigId == configId).EnableInitDb) continue; var db2 = db.GetConnectionScope(configId); var seedDataTable = seedData.ToList().ToDataTable(); seedDataTable.TableName = db.EntityMaintenance.GetEntityInfo(entityType).DbTableName; if (seedDataTable.Columns.Contains(SqlSugarConst.DefaultPrimaryKey)) { var storage = db2.Storageable(seedDataTable).WhereColumns(SqlSugarConst.DefaultPrimaryKey).ToStorage(); storage.AsInsertable.ExecuteCommand(); storage.AsUpdateable.ExecuteCommand(); } else // 没有主键或者不是预定义的主键(没主键有重复的可能) { var storage = db2.Storageable(seedDataTable).ToStorage(); storage.AsInsertable.ExecuteCommand(); } } } }