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;
///
/// 数据库上下文对象
///
public static class DbContext
{
///
/// SqlSugar 数据库实例
///
public static readonly SqlSugarScope Instance = new(
// 读取 appsettings.json 中的 ConnectionConfigs 配置节点
App.GetConfig>("ConnectionConfigs")
, db =>
{
// 这里配置全局事件,比如拦截执行 SQL
});
public static void AddSqlsugarSetup(this IServiceCollection services)
{
var configConnection = App.GetConfig>("ConnectionConfigs");
services.AddSingleton(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.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();
// // var obj = appServive?.HttpContext?.RequestServices.GetService();
// // Console.WriteLine("AOP" + obj.GetHashCode());
//};
});
return sqlSugar;
});
}
///
/// 根据命名空间和数据库连接key填表
/// 注意,只有继承了ezBaseModel 的模型才会创建
///
///
/// 配置库名
///
public static void DbCodeFirst(this IApplicationBuilder app, string ModeProjectName, string? Modenamespace = null, string? ConfigId = null)
{
var _db = app.ApplicationServices.GetService();
//切换数据库
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();
//切换数据库
if (!string.IsNullOrEmpty(ConfigId))
_db.AsTenant().ChangeDatabase(ConfigId);
//建库
_db.DbMaintenance.CreateDatabase();
_db.CodeFirst.InitTables(Obj);//根据types创建表
}
}