When using Entity Framework CTP 5 "code only," how can I retrieve the raw SQL underlying a LINQ query?

code-first ef4-code-only entity-framework profiling sql


Entity Framework CTP5 is being used by me in "code only" mode. I'm using a LINQ query on an object that the database returned since the query is moving so slowly. Is there a way for me to get the SQL statement that the query generates?

Topic currentTopic =
    (from x in Repository.Topics
     let isCurrent = (x.StoppedAt <= x.StartedAt || (x.StartedAt >= currentTopicsStartedAtOrAfter))
     where x.Meeting.Manager.User.Id == user.Id && isCurrent
     orderby x.StartedAt descending
     select x).FirstOrDefault();

A ancestor of DbContext is the "Repository" attribute.

It's a bit complex since I'm explicitly defining the logic in the query because EF can't utilize my helper methods on the objects.

Is there a way for me to export the SQL that this LINQ query will generate and save it somewhere else, like my Log4net repository?

3/1/2011 11:19:25 AM

Accepted Answer

Either utilize the Event Tracing for Windows (SQL Profiling) functionality from Performance Profiler for ANTS or SQL Trace to directly capture the query that is now executing on the server.

3/1/2011 11:30:30 AM

Popular Answer

Use Provider of Entity Framework tracing as outlined here if you want to (but it is old post for CTP3).

Your further options are:

Additionally, you may utilize common EF.ToTraceString like @Andy recommended, butDbQuery This technique is absent from CodeFirst (or I couldn't locate it).


So DbQuery doesn't possessToTraceString because the time is promptly put into actionToString .

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow