Steven Lyon
Steven Lyon

Reputation: 53

How to Log when anything is lazy-Loaded in EF6

Is there any possible way to Log when entities are lazy-loaded.

I am utilizing database first with Entity Framework 6. For it to be useful it would need to NOT log when retrieving (non-lazy) the initial entity(s) but only when Lazy-loading sub-entities. If the log had any of the following information it could be useful: raw sql for the Lazy-Load, what entity property was lazy-loaded, what line number in C# was the Lazy-Load triggered.

Upvotes: 2

Views: 382

Answers (1)

Francesc Castells
Francesc Castells

Reputation: 2847

This is an old question, but other people might have the same issue as I did.

Looking at the official EF documentation about logging, I noticed that the lazy loading query in the sample was showing a parameter called @EntityKeyValue1. As all lazy loaded queries will require at least one key parameter, I assume that this one will always be present. So, I managed to log all lazy loaded queries the following way:

  Database.Log = s =>
  {
      if (s.Contains("@EntityKeyValue1"))
      {
          Console.WriteLine($"Lazy loading query: {s}");
      }
  }; 

Upvotes: 2

Related Questions