Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In EF 4.1 DbContext how to trace generated SQL

I wonder how to trace generated SQL like DataContext in LinqToSql.

I also read articles about the solution of EFProviderWrapper on Jaroslaw Kowalski's blog, but it is based on ObjectContext, does not work for DbContext.

Anyone know how to do this in DbContext?

Thank you.

like image 207
Chance Avatar asked Apr 09 '11 05:04

Chance


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 can I see SQL query generated by LINQ in Visual Studio?

var q = from img in context. Images ... select img; string sql = q. ToString(); sql will contain the sql select query.


2 Answers

The easiest way with DbContext and DbSet<T> is just to use ToString() on the IQueryable you have built. For example:

var query = context.Blogs.Include(b => b.Posts)                    .Where(b => b.Title == "AnyTitle");  string sql = query.ToString(); 

sql contains the SQL command which will be issued to the DB when the query gets executed.

like image 169
Slauma Avatar answered Oct 14 '22 18:10

Slauma


The MVC-Mini-Profiler is a pwerful tool, not ony trace generated sql, but also profiling tool.

Using mvc-mini-profiler database profiling with Entity Framework Code First

like image 23
Chance Avatar answered Oct 14 '22 19:10

Chance