Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

How do I view the SQL generated by entity framework ?

(In my particular case I'm using the mysql provider - if it matters)

like image 968
nos Avatar asked Sep 11 '09 19:09

nos


People also ask

How do I view SQL 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 can I see EF core generated SQL in Visual Studio?

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.

How can I see SQL query generated by LINQ in Visual Studio?

If you use SQL profiler, to ensure capture of all LINQ queries from your VS debug session, use SQL Profiler 'RPC Completed' and 'SQL:BatchCompleted' events.


2 Answers

For those using Entity Framework 6 and up, if you want to view the output SQL in Visual Studio (like I did) you have to use the new logging/interception functionality.

Adding the following line will spit out the generated SQL (along with additional execution-related details) in the Visual Studio output panel:

using (MyDatabaseEntities context = new MyDatabaseEntities()) {     context.Database.Log = s => System.Diagnostics.Debug.WriteLine(s);     // query the database using EF here. } 

More information about logging in EF6 in this nifty blog series: http://blog.oneunicorn.com/2013/05/08/ef6-sql-logging-part-1-simple-logging/

Note: Make sure you are running your project in DEBUG mode.

like image 164
Matt Nibecker Avatar answered Sep 24 '22 05:09

Matt Nibecker


You can do the following:

IQueryable query = from x in appEntities              where x.id == 32              select x;  var sql = ((System.Data.Objects.ObjectQuery)query).ToTraceString(); 

or in EF6:

var sql = ((System.Data.Entity.Core.Objects.ObjectQuery)query)             .ToTraceString(); 

or in EF6.3+:

var sql = ((dynamic)flooringStoresProducts).Sql; 

That will give you the SQL that was generated.

like image 30
Nick Berardi Avatar answered Sep 21 '22 05:09

Nick Berardi