I use Entity Framework 5 with POCO entities and lazy loading proxies. In most cases I eagerly load all entities required for subsequent operations, but in some cases I rely on lazy loading to retrieve and navigate to related entities. This works well, but I would like to audit my application and make sure that I don't miss opportunities for eager loading optimization (or at least eliminate excessive use of lazy loading).
I currently rely on the SQL Profiler for this purpose, but this is tedious, because it's hard to distinguish between eager/explicit loading and lazy loading queries.
Is it possible to log lazy loading operations? Basically, I would like to Debug.Print whenever a store query is executed, as a result of lazy loading (but not when I explicitly execute a query).
Please don't provide commentary on the merits (or lack thereof) of lazy loading. I am working on a sizable application and switching at this stage would be extremely risky.
I suggest checking out this library: https://github.com/jamesmanning/EntityFramework.LazyLoadLoggingInterceptor
More specifically, this file shows an implementation of an Entity Framework DbCommandInterceptor capable of detecting lazy loading queries. At its core, it implements a ReaderExecuting method containing this hack:
// unfortunately not a better way to detect whether the load is lazy or explicit via interceptor
var stackFrames = new StackTrace(true).GetFrames();
var stackMethods = stackFrames?.Select(x => x.GetMethod()).ToList();
var dynamicProxyPropertyGetterMethod = stackMethods?
.FirstOrDefault(x =>
x.DeclaringType?.FullName.StartsWith("System.Data.Entity.DynamicProxies") == true &&
x.Name.StartsWith("get_"));
if (dynamicProxyPropertyGetterMethod == null)
{
// not in a lazy-load context, nothing to do
return;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With