In EF 4.1 DbContext how to trace generated SQL

Chance picture Chance · Apr 9, 2011 · Viewed 10.3k times · Source

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.

Answer

Slauma picture Slauma · Jul 19, 2011

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.