26
May

How to show SQL command created by Entity Framework?

Sometimes you may need to look at the command, that’s created from your i.e. LINQ query and sent to database. Let’s say you have query like this:

var q = from m in e.master
           select m.t.Length;

You can cast the q into ObjectQuery and use the ToTraceString method to see the query:

Console.WriteLine(((ObjectQuery)q).ToTraceString());

This will show you the query, that’s sent do store you’re using (mainly relational database). Neat and easy.

There's 4 Comments So Far

  • cincura.net
    June 14th, 2009 at 14:10

    Jarek Kowalski posted to MSDN Code Gallery wrappers for any ADO.NET Entity Framework provider with ability

  • wqe
    January 22nd, 2010 at 20:39

    How do you do this in case of insert/update/delete?

  • cincura.net
    January 22nd, 2010 at 21:37

    ToTraceString works only for queries. For insert etc. you have couple of options, for instance profiler, if your database engine supports this (via i.e. 3rd party product) or wrapping provider, as noted above or Entity Framework Profiler – http://www.efprof.com or …

  • Raja Venkatesh
    October 2nd, 2011 at 19:52

    Use Linq to Entity Visualizer in debug mode. Not required to ToTraceString etc. You’ll have complete LINQ to Entities query visualized on the fly. The free tool is available at http://visualstudiogallery.msdn.microsoft.com/99468ece-689b-481c-868c-19e00e0a4e69

    Good luck

    Venkat

Share your thoughts, leave a comment!