Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trace SQL Query in EF Code First

I'm using Entity Framework Code First and I'd like to be able to record all the SQL queries generated by the DbContext. In Linq to sql there was a DB log and I can't seem to find it in EF. I could then drop them in a log or output it to the page.

I'm using the version 4.1.0.0 of the EntityFramework Assembly.

like image 258
Richard Forrest Avatar asked May 29 '11 15:05

Richard Forrest


People also ask

How do I trace a SQL query?

Open SQL Server Profiler Just search for the tool on your computer where SQL server is running. It should automatically come with the installation. Once that is open you click 'file/new trace' and connect to the database similar to when opening SQL server management studio.

Which query is executed first?

The FROM clause, and subsequent JOIN s are first executed to determine the total working set of data that is being queried.

How do I view the SQL generated by the Entity Framework 6?

Visual Studio Output You can set the logging level for Microsoft to “Information”. Then you can view the SQL in the output log when running in debug mode from Visual Studio. The SQL will then be visible in the Output panel.


2 Answers

Your best bet would be to use the Entity Framework Profiler, although it's unfortunately not free.

You can also manually get the SQL it will generate by running a ToString() on the IQueryable itself, but that will have to be done on a per-query basis.

One final option is that if you are using MS Sql Server as your backend, you can load up the Sql Server Profiler (that comes with Sql Server Management Studio I believe) and log the sql statements from there.

like image 69
KallDrexx Avatar answered Oct 01 '22 12:10

KallDrexx


Miniprofiler a free alternative to entity framework profiler that will allow you to trace all sql queries made during web requests

like image 41
ITmeze Avatar answered Oct 01 '22 13:10

ITmeze