using Ewide.Core; using Ewide.Core.Cache; using Furion; using Furion.Logging.Extensions; using Microsoft.Extensions.DependencyInjection; using SqlSugar; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Ewide.Core { public static class SqlsugarSetup { public static void AddSqlsugarSetup(this IServiceCollection services) { var connList = App.GetConfig>("ConnectionStrings")?.Where(p => p.Enabled).ToList(); List connectConfigList = new(); connList.ForEach(conn => { connectConfigList.Add(new ConnectionConfig { ConfigId = conn.Id, ConnectionString = conn.ConnectionString, DbType = conn.DbType, IsAutoCloseConnection = true, InitKeyType = InitKeyType.Attribute, MoreSettings = new ConnMoreSettings() { IsAutoRemoveDataCache = true//自动清理缓存 }, ConfigureExternalServices = new ConfigureExternalServices() { DataInfoCacheService = new SqlSugarCache(), EntityNameService = (type, entity) => { var attributes = type.GetCustomAttributes(true); if (attributes.Any(it => it is TableAttribute)) { entity.DbTableName = (attributes.First(it => it is TableAttribute) as TableAttribute).Name; } }, EntityService = (type, column) => { var attributes = type.GetCustomAttributes(true); if (attributes.Any(it => it is KeyAttribute))// by attribute set primarykey { column.IsPrimarykey = true; //有哪些特性可以看 1.2 特性明细 } if (attributes.Any(it => it is ColumnAttribute)) { column.DbColumnName = (attributes.First(it => it is ColumnAttribute) as ColumnAttribute).Name; } } } }); }); services.AddSqlSugar(connectConfigList.ToArray(), db => { //处理日志事务 db.Aop.OnLogExecuting = (sql, pars) => { Debugger.Log(1, "", $"===================CurrentConfigId:{db.CurrentConnectionConfig.ConfigId} SqlSugar log started ===================\r\n"); Debugger.Log(2, "语句:", sql); Debugger.Log(3, "参数:", string.Join(",", pars?.Select(it => it.ParameterName + ":" + it.Value))); Debugger.Log(4, "", $"===================CurrentConfigId:{db.CurrentConnectionConfig.ConfigId} SqlSugar log end ===================\r\n"); //App.PrintToMiniProfiler("SqlSugar", "Info", sql + "\r\n" + db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value))); }; }); List types = App.EffectiveTypes.Where(a => !a.IsAbstract && a.IsClass && a.GetCustomAttributes(typeof(SugarTable), true)?.FirstOrDefault() != null).ToList(); SqlSugarScope sqlSugarScope = new SqlSugarScope(connectConfigList, //全局上下文生效 db => { /* * 默认只会配置到第一个数据库,这里按照官方文档进行多数据库/多租户文档的说明进行循环配置 */ foreach (var c in connectConfigList) { var dbProvider = db.GetConnectionScope((string)c.ConfigId); //执行超时时间 dbProvider.Ado.CommandTimeOut = 30; 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("Sql:" + "\r\n\r\n" + UtilMethods.GetSqlString(c.DbType, sql, pars)); App.PrintToMiniProfiler("SqlSugar", "Info", UtilMethods.GetSqlString(c.DbType, sql, pars)); $"DB:{c.ConfigId}, Sql:\r\n\r\n {UtilMethods.GetSqlString(c.DbType, sql, pars)}".LogInformation(); }; dbProvider.Aop.DataExecuting = (oldValue, entityInfo) => { //// 新增操作 //if (entityInfo.OperationType == DataFilterType.InsertByObject) //{ // // 主键(long)-赋值雪花Id // if (entityInfo.EntityColumnInfo.IsPrimarykey && entityInfo.EntityColumnInfo.PropertyInfo.PropertyType == typeof(long)) // { // var id = ((dynamic)entityInfo.EntityValue).Id; // if (id == null || id == 0) // entityInfo.SetValue(Yitter.IdGenerator.YitIdHelper.NextId()); // } // if (entityInfo.PropertyName == "CreatedTime") // 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.TENANT_ID)?.Value); // } // if (entityInfo.PropertyName == "CreatedUserId") // { // var createUserId = ((dynamic)entityInfo.EntityValue).CreatedUserId; // if (createUserId == null || createUserId == 0) // entityInfo.SetValue(App.User.FindFirst(ClaimConst.CLAINM_USERID)?.Value); // } // if (entityInfo.PropertyName == "CreatedUserName") // entityInfo.SetValue(App.User.FindFirst(ClaimConst.CLAINM_NAME)?.Value); // } //} //// 更新操作 //if (entityInfo.OperationType == DataFilterType.UpdateByObject) //{ // if (entityInfo.PropertyName == "UpdatedTime") // entityInfo.SetValue(DateTime.Now); // if (entityInfo.PropertyName == "UpdatedUserId") // entityInfo.SetValue(App.User?.FindFirst(ClaimConst.CLAINM_USERID)?.Value); // if (entityInfo.PropertyName == "UpdatedUserName") // entityInfo.SetValue(App.User?.FindFirst(ClaimConst.CLAINM_NAME)?.Value); //} }; /* * 使用 SqlSugarScope 循环配置此项的时候会覆盖整个 ConfigureExternalServices, * 移动到 New ConnectionConfig中配置 */ //db.CurrentConnectionConfig.ConfigureExternalServices = new ConfigureExternalServices() //{ // DataInfoCacheService = new SqlSugarCache()//配置我们创建的缓存类 //}; ////全局过滤器 //var superAdminViewAllData = Convert.ToBoolean(App.GetOptions().SuperAdminViewAllData); //foreach (var entityType in types) //{ // // 配置多租户全局过滤器 // //if (!entityType.GetProperty(ClaimConst.TENANT_ID).IsEmpty()) // //{ //判断实体类中包含TenantId属性 // // //构建动态Lambda // // var lambda = DynamicExpressionParser.ParseLambda // // (new[] { Expression.Parameter(entityType, "it") }, // // typeof(bool), $"{nameof(DBEntityTenant.TenantId)} == @0 or (@1 and @2)", // // GetTenantId(), IsSuperAdmin(), superAdminViewAllData); // // dbProvider.QueryFilter.Add(new TableFilterItem(entityType, lambda)); //将Lambda传入过滤器 // //} // // 配置加删除全局过滤器 // if (!entityType.GetProperty(CommonConst.DELETE_FIELD).IsEmpty()) // { //判断实体类中包含IsDeleted属性 // //构建动态Lambda // var lambda = DynamicExpressionParser.ParseLambda // (new[] { Expression.Parameter(entityType, "it") }, // typeof(bool), $"{nameof(DEntityBase.IsDeleted)} == @0", // false); // dbProvider.QueryFilter.Add(new TableFilterItem(entityType, lambda) // { // IsJoinQuery = true // }); //将Lambda传入过滤器 // } //} } }); services.AddSingleton(sqlSugarScope); // 注册 SqlSugar 仓储 services.AddScoped(typeof(SqlSugarRepository<>)); ////如果多个数数据库传 List //var configConnection = new ConnectionConfig() //{ // DbType = SqlSugar.DbType.MySql, // ConnectionString = configuration.GetConnectionString(dbName), // IsAutoCloseConnection = true, //}; //SqlSugarScope sqlSugar = new SqlSugarScope(configConnection, // db => // { // //单例参数配置,所有上下文生效 // db.Aop.OnLogExecuting = (sql, pars) => // { // //Console.WriteLine(sql);//输出sql // }; // }); //services.AddSingleton(sqlSugar);//这边是SqlSugarScope用AddSingleton } /// /// 判断是不是超级管理员 /// /// private static bool IsSuperAdmin() { if (App.User == null) return false; return App.User.FindFirst(ClaimConst.CLAINM_SUPERADMIN)?.Value == AdminType.SuperAdmin.GetHashCode().ToString(); } /// /// 添加 SqlSugar 拓展 /// /// /// /// /// public static IServiceCollection AddSqlSugar(this IServiceCollection services, ConnectionConfig config, Action buildAction = default) { var list = new List(); list.Add(config); return services.AddSqlSugar(list, buildAction); } /// /// 添加 SqlSugar 拓展 /// /// /// /// /// public static IServiceCollection AddSqlSugar(this IServiceCollection services, List configs, Action buildAction = default) { // 注册 SqlSugar 客户端 services.AddScoped(u => { var db = new SqlSugarClient(configs); buildAction?.Invoke(db); return db; }); // 注册 SqlSugar 仓储 services.AddScoped(typeof(SqlSugarRepository<>)); return services; } } public class MutiDBConnectionString { public string Id { get; set; } public string ConnectionString { get; set; } public DbType DbType { get; set; } public bool Enabled { get; set; } public string ProviderName { get; set; } } }