How to retrieve SQL generated from a LINQ to Entities query

The class ObjectQuery has a function ToTraceString. The problem is that when creating a Linq to Entities query, the query is of type IQueryable<T>. But fortunately these objects are instances of ObjectQuery<T>, so you can simply cast them.

((ObjectQuery)query).ToTraceString()

However, in other cases, it would be more interesting to cast our query ObjectQuery<T> instead of ObjectQuery. In this case, the problem is that T may be an anonymous class. Hence the idea of ​​using inference of type:

public static class ObjectQueryExtension
{
    public static ObjectQuery<T> ToObjectQuery<T>(this IQueryable<T> query)
    {
        return (ObjectQuery<T>)query;
    }
}
Enjoy this blog? Buy Me A Coffee Donate with PayPal

Leave a reply