Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the raw SQL underlying a LINQ query when using Entity Framework CTP 5 "code only"?

I've using Entity Framework CTP5 in "code only" mode. I'm running a LINQ query on a object that was return from the database, as the query is running really slowly. Is there any way in which I can get the SQL statement that is being generated from the query?

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();

The "Repository" property is a descendent of DbContext.

It's a little complicated, as EF can't use my helper methods on the objects, so I'm specifying the logic directly in the query.

So, is there any way I can dump the SQL that will be produced by that LINQ query (e.g. to my log4net repository)?

like image 757
dommer Avatar asked Mar 01 '11 11:03

dommer


People also ask

Does Entity Framework use LINQ to SQL?

Entity Framework Core uses Language-Integrated Query (LINQ) to query data from the database. LINQ allows you to use C# (or your . NET language of choice) to write strongly typed queries. It uses your derived context and entity classes to reference database objects.


2 Answers

You can try using Entity Framework tracing provider as described here (but it is old post for CTP3).

Your other choices are:

  • SQL Server Profiler - part of MS SQL Developer tools (in case your DB is SQL Server)
  • Intelli trace - only in VS 2010 Ultimate but it doesn't show parameter values
  • Hugati Query Profiler
  • Entity framework profiler

In common EF you can also use ToTraceString as @Andy suggested but DbQuery in CodeFirst doesn't have this method (or I didn't find it).

Edit:

So DbQuery doesn't have ToTraceString because it is directly implemented as ToString.

like image 69
Ladislav Mrnka Avatar answered Nov 16 '22 02:11

Ladislav Mrnka


This worked for me and it is free:

public static class DebugExtensions
{
    private static object GetPropertyValue(object o, string Name)
    {
        return o.GetType().GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public).Where(x => x.Name == Name).First().GetValue(o, null);
    }
    public static string ToTraceString(this IQueryable query)
    {
        var oquery = (ObjectQuery)GetPropertyValue(GetPropertyValue(query, "InternalQuery"), "ObjectQuery");
        return oquery.ToTraceString();
    }
}

Usage:

   var rows = db.Forecasts.Take(1);
   System.Diagnostics.Debug.WriteLine(rows.ToTraceString());
like image 29
John Avatar answered Nov 16 '22 02:11

John