liaoxujun@qq.com
2023-09-07 876292b5a092977ac84c1c1699d9f3e45b9be67d
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
121
122
123
124
125
126
127
128
129
130
131
using DocumentServiceAPI.Enum;
using DocumentServiceAPI.Utility;
using Furion;
using Furion.Logging;
using Furion.Logging.Extensions;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
 
namespace DocumentServiceAPI.Core;
 
/// <summary>
/// 数据库上下文对象
/// </summary>
public static class DbContext
{
    /// <summary>
    /// SqlSugar 数据库实例
    /// </summary>
    public static readonly SqlSugarScope Instance = new(
        // 读取 appsettings.json 中的 ConnectionConfigs 配置节点
        App.GetConfig<List<ConnectionConfig>>("ConnectionConfigs")
        , db =>
        {
            // 这里配置全局事件,比如拦截执行 SQL
           
           
        });
    public static void AddSqlsugarSetup(this IServiceCollection services)
    {
        var configConnection = App.GetConfig<List<ConnectionConfig>>("ConnectionConfigs");
        
 
 
        services.AddSingleton<ISqlSugarClient>(s =>
        {
            SqlSugarScope sqlSugar = new SqlSugarScope(configConnection,
           db =>
           {
               db.CurrentConnectionConfig.ConfigureExternalServices = new ConfigureExternalServices()
               {
                   //判断是否开启redis设置二级缓存方式
                   DataInfoCacheService = new SqlSugarRedisCache(),
                   //模型定义为 int?号时自动为可空
                   EntityService = (c, p) =>
                   {
                       /***高版C#写法***/
                       //支持string?和string  
                       if (p.IsPrimarykey == false && new NullabilityInfoContext()
                        .Create(c).WriteState is NullabilityState.Nullable)
                       {
                           p.IsNullable = true;
                       }
                   }
 
               };
               db.Aop.OnLogExecuting = (sql, pars) =>
               {
                   Console.WriteLine(sql);//输出sql,查看执行sql 性能无影响
 
 
                   //获取原生SQL推荐 5.1.4.63  性能OK
                   //UtilMethods.GetNativeSql(sql,pars)
 
                   //获取无参数化SQL 对性能有影响,特别大的SQL参数多的,调试使用
                   //UtilMethods.GetSqlString(DbType.SqlServer,sql,pars)
 
 
               };
               db.CurrentConnectionConfig.MoreSettings = new ConnMoreSettings()
               {
                   //所有 增、删 、改 会自动调用.RemoveDataCache()清理二级缓存
                   IsAutoRemoveDataCache = true
               };
               db.Aop.OnError = (exp) =>
               {
                   $"数据库执行错误了{exp}".LogInformation();
                //   NlogUtil.WriteFileLog(NLog.LogLevel.Error, LogType.Other, "SqlSugar", "执行SQL错误事件", exp);
               };
 
               //单例参数配置,所有上下文生效
               //db.Aop.OnLogExecuting = (sql, pars) =>
               //{
               //    //获取作IOC作用域对象
               //  //  var appServive = s.GetService<IHttpContextAccessor>();
               //   // var obj = appServive?.HttpContext?.RequestServices.GetService<Log>();
               // //   Console.WriteLine("AOP" + obj.GetHashCode());
               //};
           });
            return sqlSugar;
        });
    }
 
    /// <summary>
    /// 根据命名空间和数据库连接key填表
    /// 注意,只有继承了ezBaseModel 的模型才会创建
    /// </summary>
    /// <param name="app"></param>
    /// <param name="ConfigId">配置库名</param>
    /// <param name="ModeProjectName"></param>
    public static void DbCodeFirst(this IApplicationBuilder app, string ModeProjectName, string? Modenamespace = null, string? ConfigId = null)
    {
      
        var _db = app.ApplicationServices.GetService<ISqlSugarClient>();
        //切换数据库
        if (!string.IsNullOrEmpty(ConfigId))
            _db.AsTenant().ChangeDatabase(ConfigId);
 
        //建库
        _db.DbMaintenance.CreateDatabase();
        Type[]? types = UtilityFun.GetAllAssembly().Where(x => x.FullName.Contains(ModeProjectName + ",")).FirstOrDefault()?.GetTypes().WhereIF(!string.IsNullOrEmpty(Modenamespace), name => name.FullName.Contains(Modenamespace + ".")).ToArray().Where(x => x.IsSubclassOf(typeof(BaseModel))).ToArray();
 
        _db.CodeFirst.InitTables(types);//根据types创建表
 
    }
    public static void DbCodeFirst(this IApplicationBuilder app, Type Obj,  string? ConfigId = null)
    {
        var _db = app.ApplicationServices.GetService<ISqlSugarClient>();
        //切换数据库
        if (!string.IsNullOrEmpty(ConfigId))
            _db.AsTenant().ChangeDatabase(ConfigId);
        //建库
        _db.DbMaintenance.CreateDatabase();
        _db.CodeFirst.InitTables(Obj);//根据types创建表
    }
}