using Microsoft.EntityFrameworkCore.Diagnostics; using MySqlConnector; using System.Data.Common; using System.Diagnostics; using System.Text.RegularExpressions; namespace YLErp.DataBase.Interceptors { internal class DgDbCommandInterceptor : DbCommandInterceptor { public override InterceptionResult ReaderExecuting( DbCommand command, CommandEventData eventData, InterceptionResult result) { DebugWrite(command); return result; } public override ValueTask> ReaderExecutingAsync( DbCommand command, CommandEventData eventData, InterceptionResult result, CancellationToken cancellationToken = default) { DebugWrite(command); return new ValueTask>(result); } private static void DebugWrite(DbCommand dbCommand) { Debug.WriteLine("-------带参数的SQL-------"); Debug.WriteLine(dbCommand.CommandText); Debug.WriteLine("-------参数替换后的SQL-------"); var rawSQL= Regex.Replace(dbCommand.CommandText, "@[_a-zA-Z0-9]+", new MatchEvaluator(m => { var para = dbCommand.Parameters[m.Value]; var value = para.Value?.ToString(); if (value == null) { return "null"; } switch (para.DbType) { case System.Data.DbType.String: case System.Data.DbType.StringFixedLength: case System.Data.DbType.AnsiString: case System.Data.DbType.AnsiStringFixedLength: case System.Data.DbType.Date: case System.Data.DbType.DateTime: case System.Data.DbType.DateTime2: case System.Data.DbType.DateTimeOffset: return string.Concat("'", MySqlHelper.EscapeString(value),"'"); default: return value; } })); Debug.WriteLine(rawSQL); } public static readonly DgDbCommandInterceptor Default; static DgDbCommandInterceptor() { Default = new DgDbCommandInterceptor(); } } }