نمایش خروجی SQL کدهای Entity framework 6 در کنسول دیباگ ویژوال استودیو
نویسنده: وحید نصیری
تاریخ: ۱۳۹۲/۰۸/۱۲ ۱۱:۱۵
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
using System;
using System.Data.Common;
using System.Data.Entity.Infrastructure.Interception;
using System.Diagnostics;
using System.Text;
namespace EFCommandInterception
{
public class SimpleInterceptor : DbCommandInterceptor
{
public override void ScalarExecuting(DbCommand command, DbCommandInterceptionContext<object> interceptionContext)
{
var timespan = runCommand(() => base.ScalarExecuting(command, interceptionContext));
logData(command, interceptionContext.Exception, timespan);
}
public override void NonQueryExecuting(DbCommand command, DbCommandInterceptionContext<int> interceptionContext)
{
var timespan = runCommand(() => base.NonQueryExecuting(command, interceptionContext));
logData(command, interceptionContext.Exception, timespan);
}
public override void ReaderExecuting(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
{
var timespan = runCommand(() => base.ReaderExecuting(command, interceptionContext));
logData(command, interceptionContext.Exception, timespan);
}
private static Stopwatch runCommand(Action command)
{
var timespan = Stopwatch.StartNew();
command();
timespan.Stop();
return timespan;
}
private static void logData(DbCommand command, Exception exception, Stopwatch timespan)
{
if (exception != null)
{
Trace.TraceError(formatException(exception, "Error executing command: {0}", command.CommandText));
}
else
{
Trace.TraceInformation(string.Concat("Elapsed time: ", timespan.Elapsed, " Command: ", command.CommandText));
}
}
private static string formatException(Exception exception, string fmt, params object[] vars)
{
var sb = new StringBuilder();
sb.Append(string.Format(fmt, vars));
sb.Append(" Exception: ");
sb.Append(exception.ToString());
while (exception.InnerException != null)
{
sb.Append(" Inner exception: ");
sb.Append(exception.InnerException.ToString());
exception = exception.InnerException;
}
return sb.ToString();
}
}
} DbInterception.Add(new SimpleInterceptor());
public MyContext():base("MyConnectionString")
{
Database.Log = sql => Debug.Write(sql);
} <interceptors> <interceptor type="System.Data.Entity.Infrastructure.Interception.DatabaseLogger, EntityFramework"> <parameters> <parameter value="C:\Temp\LogOutput.txt"/> <parameter value="true" type="System.Boolean"/> </parameters> </interceptor> </interceptors>