73 lines
3.3 KiB
C#
73 lines
3.3 KiB
C#
using System.ComponentModel.DataAnnotations;
|
|
using System.Reflection;
|
|
using JNPF;
|
|
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) =>
|
|
// {
|
|
// 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}");
|
|
// };
|
|
//});
|
|
});
|
|
|
|
return services;
|
|
}
|
|
} |