Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework How to see SQL statements for SaveChanges method

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?

like image 399
LCJ Avatar asked Jul 20 '12 11:07

LCJ


People also ask

How can I see the SQL statement generated by Entity Framework?

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.

How do I use SaveChanges in Entity Framework?

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 .

What does the DbContext SaveChanges () method return?

Returns. The number of state entries written to the underlying database. This can include state entries for entities and/or relationships.


1 Answers

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

like image 163
Alex Klaus Avatar answered Oct 07 '22 16:10

Alex Klaus