How to retrieve SQL generated from a LINQ to Entities query

 
 
  • Gérald Barré

The ObjectQuery class exposes a ToTraceString method that returns the SQL generated by a query. When writing a LINQ to Entities query, the result is typed as IQueryable<T>. Fortunately, these objects are actually instances of ObjectQuery<T>, so a simple cast is all that's needed:

C#
((ObjectQuery)query).ToTraceString()

In some cases, casting to ObjectQuery<T> is preferable over ObjectQuery. However, T may be an anonymous type, making an explicit cast difficult to write. Type inference solves this with a simple extension method:

C#
public static class ObjectQueryExtension
{
    public static ObjectQuery<T> ToObjectQuery<T>(this IQueryable<T> query)
    {
        return (ObjectQuery<T>)query;
    }
}

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?