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.

103 lines
3.6 KiB
C#

using SqlSugar;
using System;
using Serilog;
using EntrustSettle.Common.LogHelper;
using EntrustSettle.Model;
namespace EntrustSettle.Common.DB.Aop;
9 months ago
//namespace EntrustSettle.Common.DB.Aop;
public static class SqlSugarAop
{
public static void OnLogExecuting(ISqlSugarClient sqlSugarScopeProvider, string user, string table, string operate, string sql, SugarParameter[] p, ConnectionConfig config)
{
try
{
if (!AppSettings.app(new string[] { "AppSettings", "SqlAOP", "Enabled" }).ObjToBool()) return;
if (AppSettings.app(new string[] { "AppSettings", "SqlAOP", "LogToConsole", "Enabled" }).ObjToBool() ||
AppSettings.app(new string[] { "AppSettings", "SqlAOP", "LogToFile", "Enabled" }).ObjToBool() ||
AppSettings.app(new string[] { "AppSettings", "SqlAOP", "LogToDB", "Enabled" }).ObjToBool())
{
using (LogContextExtension.Create.SqlAopPushProperty(sqlSugarScopeProvider))
{
Log.Information("------------------ \r\n User:[{User}] Table:[{Table}] Operate:[{Operate}] ConnId:[{ConnId}]【SQL语句】: \r\n {Sql}",
user, table, operate, config.ConfigId, UtilMethods.GetNativeSql(sql, p));
}
}
}
catch (Exception e)
{
Log.Error("Error occured OnLogExcuting:" + e);
}
}
public static void DataExecuting(object oldValue, DataFilterModel entityInfo)
{
if (entityInfo.EntityValue is RootEntityTkey<long> rootEntity)
{
if (rootEntity.Id == 0)
{
rootEntity.Id = SnowFlakeSingle.Instance.NextId();
}
}
if (entityInfo.EntityValue is BaseEntity baseEntity)
{
// 新增操作赋值CreateTime
if (entityInfo.OperationType == DataFilterType.InsertByObject)
{
if (baseEntity.CreateTime == DateTime.MinValue)
{
baseEntity.CreateTime = DateTime.Now;
}
}
// 更新操作赋值ModifyTime
if (entityInfo.OperationType == DataFilterType.UpdateByObject)
{
baseEntity.ModifyTime = DateTime.Now;
}
9 months ago
//if (App.User?.ID > 0)
if (!string.IsNullOrEmpty(App.User?.ID))
{
9 months ago
// 这里不需要用到租户
//if (baseEntity is ITenantEntity tenant && App.User.TenantId > 0)
//{
// if (tenant.TenantId == 0)
// {
// tenant.TenantId = App.User.TenantId;
// }
//}
switch (entityInfo.OperationType)
{
case DataFilterType.InsertByObject:
9 months ago
if (baseEntity.CreateBy.IsNullOrEmpty() || baseEntity.CreateId is null or "")
{
baseEntity.CreateId = App.User.ID;
baseEntity.CreateBy = App.User.Name;
}
break;
case DataFilterType.UpdateByObject:
baseEntity.ModifyId = App.User.ID;
baseEntity.ModifyBy = App.User.Name;
break;
}
}
}
}
private static string GetParas(SugarParameter[] pars)
{
string key = "【SQL参数】";
foreach (var param in pars)
{
key += $"{param.ParameterName}:{param.Value}\n";
}
return key;
}
}