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.
C#
((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:
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!
Enjoy this blog?💖 Sponsor on GitHub