using System.Data; using System.Data.Common; using System.Text; using System.Threading; using System.Threading.Tasks; using EasyDevCore.Common; using Microsoft.EntityFrameworkCore.Diagnostics; namespace EasyDevCore.Database { /// /// /// /// public class EasyCommandInterceptor: DbCommandInterceptor { /// /// Initializes a new instance of the class. /// public EasyCommandInterceptor() { } /// /// Called when execution of a command has failed with an exception. /// /// The command. /// Contextual information about the command and execution. /// The cancellation token. /// /// A representing the asynchronous operation. /// public override Task CommandFailedAsync(DbCommand command, CommandErrorEventData eventData, CancellationToken cancellationToken = default) { if (eventData.Exception != null) { eventData.Exception.Data["CommandText"] = GetSQLText(command); } return base.CommandFailedAsync(command, eventData, cancellationToken); } /// /// Called when execution of a command has failed with an exception. /// /// The command. /// Contextual information about the command and execution. public override void CommandFailed(DbCommand command, CommandErrorEventData eventData) { if(eventData.Exception != null) { eventData.Exception.Data["CommandText"] = GetSQLText(command); } base.CommandFailed(command, eventData); } /// /// Gets the SQL text. /// /// The command. /// private static string GetSQLText(DbCommand command) { StringBuilder sb = new(); sb.AppendLine($"Source : {command.Connection.DataSource}"); sb.AppendLine($"Database : {command.Connection.Database}"); sb.AppendLine($"Connection time out : {command.Connection.ConnectionTimeout}"); sb.AppendLine($"Query Type : {command.CommandType}"); sb.AppendLine($"Command time out : {command.CommandTimeout}"); sb.AppendLine($"SQL Text : {command.CommandText}"); foreach(DbParameter p in command.Parameters) { sb.AppendLine(string.Format(" ?{0}{1}({2}) = {3}", (p.Direction == ParameterDirection.Input ? "" : "="), p.ParameterName, p.DbType, (p.DbType.ToString().HasAny(System.StringComparison.InvariantCultureIgnoreCase, "string", "date", "time") ? $"'{p.Value}'" : $"{p.Value}"))); } return sb.ToString(); } } }