check out this link... it has a tracing provider for EF4.
I'll try to give an example based on how I'm using this in a unit test.
Step 1: Register the provider
There are a couple ways to configure the provider. For my unit tests I configured the provider in code by calling the static method RegisterProvider();
[AssemblyInitialize()]
public static void AssemblyInit(TestContext context) {
EFTracingProviderConfiguration.RegisterProvider();
}
Step 2: Create a sub-class of your entity model to provide the tracing extensions
public partial class ExtendedNorthwindEntities : NorthwindEntities {
private TextWriter logOutput;
public ExtendedNorthwindEntities(string connectionString)
: base(EntityConnectionWrapperUtils.CreateEntityConnectionWithWrappers(
connectionString,
"EFTracingProvider")) {
}
#region Tracing Extensions
private EFTracingConnection TracingConnection {
get { return this.UnwrapConnection<EFTracingConnection>(); }
}
public event EventHandler<CommandExecutionEventArgs> CommandExecuting {
add { this.TracingConnection.CommandExecuting += value; }
remove { this.TracingConnection.CommandExecuting -= value; }
}
public event EventHandler<CommandExecutionEventArgs> CommandFinished {
add { this.TracingConnection.CommandFinished += value; }
remove { this.TracingConnection.CommandFinished -= value; }
}
public event EventHandler<CommandExecutionEventArgs> CommandFailed {
add { this.TracingConnection.CommandFailed += value; }
remove { this.TracingConnection.CommandFailed -= value; }
}
private void AppendToLog(object sender, CommandExecutionEventArgs e) {
if (this.logOutput != null) {
this.logOutput.WriteLine(e.ToTraceString().TrimEnd());
this.logOutput.WriteLine();
}
}
public TextWriter Log {
get { return this.logOutput; }
set {
if ((this.logOutput != null) != (value != null)) {
if (value == null) {
CommandExecuting -= AppendToLog;
}
else {
CommandExecuting += AppendToLog;
}
}
this.logOutput = value;
}
}
#endregion
}
Step 3: Attach to the Log property
var context = new ExtendedNorthwindEntities("name="NorthwindEntities"");
context.Log = System.Console.Out;
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…