You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

228 lines
10 KiB
C#

12 months ago
using DS.Module.Core;
using DS.Module.Core.Data;
12 months ago
using DS.Module.Core.Extensions;
using DS.Module.Core.Log;
12 months ago
using DS.Module.UserModule;
using Microsoft.AspNetCore.Http;
12 months ago
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
12 months ago
using SqlSugar;
namespace DS.Module.SqlSugar;
/// <summary>
/// SqlSugar 启动服务
/// </summary>
public static class SqlsugarInstall
{
// /// <summary>
// /// 数据库连接字符串
// /// </summary>
// private static string DbInfo = AppSetting.Configuration["ConnectionStrings:DbInfo"];
//
// /// <summary>
// /// 数据库类型
// /// </summary>
// private static string DbType = AppSetting.Configuration["ConnectionStrings:DbType"];
//public static readonly Logger Logger = LogManager.GetCurrentClassLogger();
12 months ago
// private readonly IUser user;
// private ILogger<SqlsugarInstall> _logger;
/// <summary>
/// 将模块服务添加到依赖注入服务容器中
/// </summary>
/// <param name="services">依赖注入服务容器</param>
/// <returns></returns>
public static IServiceCollection AddSqlSugarInstall(this IServiceCollection services)
12 months ago
{
if (services == null) throw new ArgumentNullException(nameof(services));
Console.WriteLine("开始加载sqlsugar模块");
Console.WriteLine("数据库配置id:" + AppSetting.app(new string[] { "DBInfo", "DefaultDbConnId" }));
var dbs = AppSetting.app<DbConfig>("DBInfo", "DBS");
//默认数据库
List<DbConfig> dbList = new List<DbConfig>();
DbConfig defaultdb = new DbConfig()
{
ConnId = AppSetting.app(new string[] { "DBInfo", "DefaultDbConnId" }),
Connection = AppSetting.app(new string[] { "DBInfo", "DefaultDbString" }),
DbType = AppSetting.app(new string[] { "DBInfo", "DefaultDbType" }).ObjToInt()
};
dbList.Add(defaultdb);
//业务数据库集合
foreach (var item in dbs)
{
dbList.Add(item);
}
var connectConfigList = SqlsugarHelper.ReturnConnectionConfig(dbList);
//foreach (var item in dbList)
//{
// //防止数据库重复,导致的事务异常
// if (connectConfigList.Any(a => a.ConfigId == (dynamic)item.ConnId || a.ConnectionString == item.Connection))
// {
// continue;
// }
// connectConfigList.Add(new ConnectionConfig()
// {
// ConnectionString = item.Connection,
// DbType = (DbType)item.DbType,
// IsAutoCloseConnection = true,
// ConfigId = item.ConnId,
// InitKeyType = InitKeyType.Attribute,
// MoreSettings = new ConnMoreSettings()
// {
// IsAutoRemoveDataCache = true //自动清理缓存
// },
// // 自定义特性
// ConfigureExternalServices = new ConfigureExternalServices()
// {
// }
// });
//}
var httpContextAccessor = services.GetService<IHttpContextAccessor>();
var user = services.GetService<IUser>();
if (user.IsNullOrEmpty())
{
user = new AspNetUser(httpContextAccessor)
{
UserId = "1288018625843826688",
TenantId = "1288018625843826688",
CompanyId = "1288018625843826688",
OrgId = "1288018625843826688"
};
}
12 months ago
//全局上下文生效
SqlSugarScope sqlSugar = new SqlSugarScope(connectConfigList,
db =>
{
// 封装AOP
// SqlsugarAopHelper.AopForSqlsugar(db, user, dbList, connectConfigList);
Console.WriteLine("开始加载sqlsugar模块 要走过滤 起了");
foreach (var c in connectConfigList)
{
var dbProvider = db.GetConnectionScope((string)c.ConfigId);
// var user = services.GetService<IUser>();
//单例参数配置,所有上下文生效
dbProvider.Ado.CommandTimeOut = 30;
dbProvider.Aop.OnLogExecuting = (sql, pars) =>
{
//执行前事件
//Logger.Log(LogLevel.Info,
// DateTime.Now.ToString() + "\r\n" +
// UtilMethods.GetSqlString(c.DbType, sql, pars));
Console.WriteLine("执行的sql:" + sql);
};
//数据处理事件
dbProvider.Aop.DataExecuting = (oldValue, entityInfo) =>
{
// 新增操作
if (entityInfo.OperationType == DataFilterType.InsertByObject)
{
if (entityInfo.PropertyName == "Id")
{
if (entityInfo.EntityColumnInfo.PropertyInfo.PropertyType == typeof(string))
{
entityInfo.SetValue(GuidHelper.GetSnowflakeId());
}
if (entityInfo.EntityColumnInfo.IsPrimarykey &&
entityInfo.EntityColumnInfo.PropertyInfo.PropertyType == typeof(long))
{
var id = entityInfo.EntityColumnInfo.PropertyInfo.GetValue(entityInfo
.EntityValue);
if (id == null || (long)id == 0)
entityInfo.SetValue(SnowFlakeSingle.Instance.NextId());
}
}
if (entityInfo.PropertyName == "CreateTime")
entityInfo.SetValue(DateTime.Now);
if (entityInfo.PropertyName == "TenantId")
{
var tenantId = ((dynamic)entityInfo.EntityValue).TenantId;
if (tenantId == null || tenantId == 0)
entityInfo.SetValue(user.GetTenantId());
}
if (entityInfo.PropertyName == "CreateBy")
{
if (!user.UserId.IsNullOrEmpty())
{
entityInfo.SetValue(user.UserId);
}
else
{
entityInfo.SetValue(1288018625843826688);
}
}
if (entityInfo.PropertyName == "Deleted")
entityInfo.SetValue(false);
}
// 更新操作
if (entityInfo.OperationType == DataFilterType.UpdateByObject)
{
if (entityInfo.PropertyName == "UpdateTime")
entityInfo.SetValue(DateTime.Now);
if (entityInfo.PropertyName == "UpdateBy" && user != null)
entityInfo.SetValue(user.UserId);
}
};
dbProvider.Aop.OnDiffLogEvent = it =>
{
//排除日志库操作
if (Convert.ToInt64(c.ConfigId) != 1288018625843826680)
{
#region 插入日志审计表
//操作前记录 包含: 字段描述 列名 值 表名 表描述
var editBeforeData = it.BeforeData; //插入Before为null之前还没进库
//操作后记录 包含: 字段描述 列名 值 表名 表描述
var editAfterData = it.AfterData;
var sql = it.Sql;
var parameter = it.Parameters;
var data = it.BusinessData; //这边会显示你传进来的对象
var time = it.Time;
var diffType = it.DiffType; //enum insert 、update and delete
var diffData = SqlSugarDiffUtil.GetDiff(editBeforeData,editAfterData);
var auditData = new SysLogAudit()
{
KeyId =Convert.ToInt64(diffData.Id),
Sql = it.Sql,
Param = JsonConvert.SerializeObject(it.Parameters),
OperateType = diffType.ToString(),
OldValue = JsonConvert.SerializeObject(editAfterData),
NewValue = JsonConvert.SerializeObject(editAfterData),
DiffData = diffData.DiffData,
AopData = JsonConvert.SerializeObject(it.BusinessData),
// CreateUser = user.UserName
};
db.GetConnection(1288018625843826680).Insertable(auditData).ExecuteCommand();
#endregion
}
};
//全局过滤租户
dbProvider.QueryFilter.AddTableFilter<ITenantId>(m => m.TenantId == user.GetTenantId());
//全局过滤机构Id
dbProvider.QueryFilter.AddTableFilter<IOrgId>(m => m.OrgId == user.GetOrgId());
//全局软删除过滤
dbProvider.QueryFilter.AddTableFilter<IDeleted>(m => m.Deleted == false);
}
12 months ago
});
services.AddSingleton<ISqlSugarClient>(sqlSugar); //这边是SqlSugarScope用AddSingleton
return services;
}
}