This question already has an answer here:
According this thread, we can log the generated SQL
via EF
, but what about DbContext.SaveChanges()
? Is there any easy way to do this job without any extra frameworks?
This question already has an answer here:
According this thread, we can log the generated SQL
via EF
, but what about DbContext.SaveChanges()
? Is there any easy way to do this job without any extra frameworks?
In entity framework 6.0, the Database class has a property
Action<string> Log
. so setting up logging is as easy as:For more advanced needs you can set up an interceptor. More info on the entity framework wiki
Tom Regan's code updated for EF6.
You can use SQL Server Profiler and run it against the database server you are connecting to.
For short-term logging, I just put into DbContext constructor:
Pretty fast to add/remove logging of SQL. For long-use term, can be wrapped in checks with
If you want to capture the actual SQL that has been generated using EF6 (maybe to play back later) using an interceptor, you can do the following.
Create your interceptor
And you also need to register your interceptor. If you're doing this within an ASP.NET application make sure you only do it once, otherwise you'll end up intercepting the same request multiple times.
Example DAO
This does the same thing, but for every time you use your context it will write the sql query in the output window. The difference is that it does not compile in release.
This StackOverflow Explains the Difference between Trace and Debug.