Richard Forrest
Richard Forrest

Reputation: 3616

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.

Upvotes: 18

Views: 8614

Answers (4)

Alexander Shapovalov
Alexander Shapovalov

Reputation: 311

I'll just leave it here.

public class Context : DbContext
{
    public Context(string connectionString) : base(connectionString)
    { Database.Log = Console.Write;  }
}

Upvotes: 1

ITmeze
ITmeze

Reputation: 1922

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

Upvotes: 1

Manuel Castro
Manuel Castro

Reputation: 2470

With tools like EF it becomes more important than ever to use the SQL Server Profiler, and it should be the primary tool used for this type of situations, if it was important when we actually wrote the queries it is even more important now that these tools build the queries for us, it's a must not only for debugging but also for optimization

Upvotes: 0

KallDrexx
KallDrexx

Reputation: 27803

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.

Upvotes: 6

Related Questions