TAGS :Viewed: 12 - Published at: a few seconds ago

[ Eager loading and navigation properties ]

var ret = (from f in context.foo
           join b in context.bar on f.barid = b.barid
           select f).ToList();

my returning list cointains all foos that have a barId, it also contains all navigation properties. What I mean by that is,

context.foo.mark is populated even though I didnt not explicitly include it nor did i access it during the query. I have lazy loading turned on, why is this occuring?

To elaborate on my question, somehow my related entities are getting loaded from the above query.I am curious as to how that is occurring, I have lazy loading enabled and I am not accessing any of the related objects

Answer 1

The lazy loading inspection is kind of a "catch-22" type problem. With Lazy Loading turned on, even a call to the property from the debugger will load the results as long as your context is still hanging around. Furthermore, if your context is still open from other queries, EF will maintain the state of those objects automatically and include them.

The only real way I can think of to determine if it is being lazily loaded or not is to inspect the SQL code sent to your database.

First, add this line to your DbContext constructor:

this.Database.Log = s => System.Diagnostics.Debug.WriteLine(s); //remove in production

Then, run your code as normal (but don't stop in the debugger to inspect your object). Look at your debug console and inspect the SQL calls made. My bet is that the SQL will not include the related properties.

If you run the code again, and stop the debugger to inspect the object properties, you should see another SQL call in the debug console fetching the related entities.