Files
tnb.server/apihost/Tnb.API.Entry/Extensions/SqlSugarConfigureExtensions.cs
pofi a4ed390e82 1. 雪花ID使用配置项
2. 使用自定义日志格式
3. 修复数据模型和新建流程的bug
2023-03-14 20:36:51 +08:00

75 lines
2.8 KiB
C#

using System.ComponentModel.DataAnnotations;
using System.Reflection;
using JNPF;
using JNPF.Logging;
using Spire.Xls;
using SqlSugar;
namespace Microsoft.Extensions.DependencyInjection;
/// <summary>
/// SqlSugar配置拓展.
/// </summary>
public static class SqlSugarConfigureExtensions
{
public static IServiceCollection SqlSugarConfigure(this IServiceCollection services)
{
// 获取选项
ConnectionStringsOptions connectionStrings = App.GetConfig<ConnectionStringsOptions>("ConnectionStrings", true);
List<ConnectionConfig> connectConfigList = new List<ConnectionConfig>();
string? connectionStr = connectionStrings.DefaultConnection;
var dataBase = connectionStrings.DBName;
var DBType = (DbType)Enum.Parse(typeof(DbType), connectionStrings.DBType);
var ConfigId = connectionStrings.ConfigId;
var DBName = connectionStrings.DBName;
// 默认数据库
connectConfigList.Add(new ConnectionConfig
{
ConnectionString = string.Format(connectionStr, DBName),
DbType = DBType,
IsAutoCloseConnection = true,
ConfigId = ConfigId,
InitKeyType = InitKeyType.Attribute,
MoreSettings = new ConnMoreSettings()
{
IsAutoRemoveDataCache = true // 自动清理缓存
},
});
services.AddSqlSugar(connectConfigList, client =>
{
//connectConfigList.ForEach(config =>
//{
// var db = ((SqlSugarScope)client).GetConnectionScope((string)config.ConfigId);
// // 设置超时时间
// db.Ado.CommandTimeOut = 30;
// // 打印SQL语句
// db.Aop.OnLogExecuting = (sql, pars) =>
// {
// var oldColor = Console.ForegroundColor;
// Console.ForegroundColor = ConsoleColor.Green;
// var finalSql = UtilMethods.GetSqlString(db.CurrentConnectionConfig.DbType, sql, pars);
// Console.WriteLine($"【{DateTime.Now.ToString("HH:mm:ss.fff")}——SQL执行完成】{db.Ado.SqlExecutionTime.TotalMilliseconds} ms");
// Console.WriteLine(finalSql);
// Console.ForegroundColor = oldColor;
// if (db.Ado.SqlExecutionTime.TotalMilliseconds > 3000)
// {
// Log.Warning($"慢查询: {db.Ado.SqlExecutionTime.TotalMilliseconds}ms, SQL: " + finalSql);
// }
// Console.WriteLine();
// };
// db.Aop.OnError = (ex) =>
// {
// Log.Error(UtilMethods.GetSqlString(db.CurrentConnectionConfig.DbType, ex.Sql, (SugarParameter[])ex.Parametres));
// };
//});
});
return services;
}
}