z8018
2026-02-11 b8fb68b44c29e4667f6ea5746119413809a60a9e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
using KH.WMS.Core.Constants;
using KH.WMS.Core.Database.UnitOfWorks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using SqlSugar;
using StackExchange.Profiling;
 
namespace KH.WMS.Core.Database.SqlSugar;
 
/// <summary>
/// SQL Sugar 配置
/// </summary>
public static class SqlSugarSetup
{
    /// <summary>
    /// 添加 SQL Sugar 服务
    /// </summary>
    public static IServiceCollection AddSqlSugar(this IServiceCollection services, IConfiguration configuration)
    {
        services.Configure<DatabaseOptions>(configuration.GetSection(AppSettingsConstants.DbConnection));
 
        Console.WriteLine("SqlSugar 正在初始化数据库连接...");
 
        services.AddSingleton<ISqlSugarClient>(provider =>
        {
            var options = provider.GetRequiredService<IOptions<DatabaseOptions>>().Value;
            var logger = provider.GetService<ILogger<SqlSugarClient>>();
 
            var config = new ConnectionConfig
            {
                ConnectionString = options.ConnectionString,
                DbType = GetDbType(options.DbType),
                IsAutoCloseConnection = true,
                InitKeyType = InitKeyType.Attribute,
                AopEvents = new AopEvents
                {
                    OnLogExecuting = (sql, pars) =>
                    {
                        var paramStr = string.Join(", ", pars.Select(p => $"{p.ParameterName}={p.Value}"));
                        Parallel.For(0, 1, e =>
                        {
                            MiniProfiler.Current.CustomTiming("SQL:", paramStr + "【SQL语句】:" + sql);
                        });
 
                        // 使用 Verbose 级别记录每一行 SQL 执行
                        if (options.EnableSqlLog && logger != null)
                        {
                            logger.LogTrace("[SQL执行] {Sql} | 参数: {Params}", sql, paramStr);
                        }
 
                        // 开发环境同时输出到控制台
                        if (options.EnableSqlLog)
                        {
                            Console.WriteLine($"SQL: {sql}\nPARAMS: {paramStr}");
                        }
                    }
                },
            };
 
            // 开发环境打印SQL
            if (options.EnableSqlLog)
            {
                config.ConfigureExternalServices = new ConfigureExternalServices
                {
                    //SqlFuncServices = new SqlFuncExternalService(),
                    EntityService = null,
                     //DataInfoCacheService =
                };
            }
 
            return new SqlSugarClient(config);
        });
 
        //services.AddScoped<IDbContext, SqlSugarDbContext>();
        //services.AddScoped<IUnitOfWork, UnitOfWork>();
 
        return services;
    }
 
    private static DbType GetDbType(string dbType)
    {
        return dbType.ToLower() switch
        {
            AppSettingsConstants.DbType_MySql => DbType.MySql,
            AppSettingsConstants.DbType_SqlServer => DbType.SqlServer,
            AppSettingsConstants.DbType_PostgreSql => DbType.PostgreSQL,
            AppSettingsConstants.DbType_Oracle => DbType.Oracle,
            AppSettingsConstants.DbType_Sqlite => DbType.Sqlite,
            _ => DbType.SqlServer
        };
    }
}
 
/// <summary>
/// 数据库配置选项
/// </summary>
public class DatabaseOptions
{
    /// <summary>
    /// 连接字符串
    /// </summary>
    public string ConnectionString { get; set; } = string.Empty;
 
    /// <summary>
    /// 数据库类型
    /// </summary>
    public string DbType { get; set; } = AppSettingsConstants.DbType_SqlServer;
 
    /// <summary>
    /// 是否启用SQL日志
    /// </summary>
    public bool EnableSqlLog { get; set; } = true;
 
    /// <summary>
    /// 命令超时时间(秒)
    /// </summary>
    public int CommandTimeout { get; set; } = 30;
}