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?
To view the SQL that will be generated, simply call ToTraceString() . You can add it into your watch window and set a breakpoint to see what the query would be at any given point for any LINQ query. You can attach a tracer to your SQL server of choice, which will show you the final query in all its gory detail.
The SaveChanges method of the DbContext prepares the Insert , Update & Delete Queries. It does so by tracking the changes to each of the entities' Context is tracking. Whenever we query the database for entities, the Context retrieves them and mark the entity as Unchanged .
Returns. The number of state entries written to the underlying database. This can include state entries for entities and/or relationships.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With