Entity Framework 4.0: How to see SQL statements for SaveChanges method

.net c# entity-framework

Question

I used to use the context.Log for tracing LINQ to SQL generated SQL Statements as shown in Sql Server Query Visualizer – Cannot see generated SQL Query

context.Log = new OutputWindowWriter();

For EF, is there anything similar and easy like the above approach?

1
30
5/23/2017 12:33:35 PM

Accepted Answer

In general you can hook up the built-in tracer or any logger by simple

context.Database.Log = msg => Trace.WriteLine(msg);

in the DbContext constructor. See more in MSDN. Some other approaches from MS are here (all based on DataContext.Log property).

Talking about the Clutch solution mentioned by Nate, it doesn't work with EF v6 (see this bug-report).

REFERENCES

  1. Logging and Intercepting Database Operations (EF6 Onwards)
  2. Logging and Intercepting Database Operations

28
6/6/2014 3:23:24 AM

Popular Answer

The Clutch.Diagnostics.EntityFramework (available in NuGet) works perfectly for me, and it's simpler than the EFTracingProvider.

UPDATE for EF 6:

Starting with Entity Framework 6, anytime Entity Framework sends a command to the database this command can be intercepted by application code. This is most commonly used for logging SQL, but can also be used to modify or abort the command.

Specifically, EF includes:
* A Log property for the context similar to DataContext.Log in LINQ to SQL.
* A mechanism to customize the content and formatting of the output sent to the log.
* Low-level building blocks for interception giving greater control/flexibility.

See http://msdn.microsoft.com/en-US/data/dn469464



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow