I am having problems understanding lazy loading in Entity Framework 5. I understand when using lazy loading related entities are not loaded until requested:
“When using Lazy Loading, your initial query only brings in the target
entity set. But whenever you access a navigation property, another
query is issued against the store to load the related entity.
(reference)”
I have a ASP.NET Web API project with two classes:
public class Farm
{
public int FarmId { get; set; }
public virtual ICollection<LandUnit> LandUnits { get; set; }
...
}
public class LandUnit
{
public int LandUnitId { get; set; }
...
}
I set LazyLoadingEnabled = true, and have my POCO classes conforming to the guidelines (reference), but when I use scaffolding to create a FarmController and call it through fiddler, it shows:
JSON
{}
...
LandUnits
{}
...
If I set LazyLoadingEnabled = false, then I get:
JSON
{}
...
LandUnits=(null)
Am I misunderstanding the basics of lazy loading? It appears to me that what is occurring is the opposite of what the definition states. When lazy loading is off, related entities are not loaded. When lazy loading is on, related entities are loaded.
This is expected behaviour. When the JSON serializer comes to serialize the type, it will enumerate the
LandUnitsnavigation property which will of course invoke the lazy load of that collection from the database.When you switch lazy loading off, your navigation property will still be set to its default value as demonstrated, as no proxy type will be generated by Entity Framework.
I would recommend keeping lazy loading switched off, and eagerly (using the
Includemethod) or explicly loading (using theLoadmethod) the related data to ensure you aren’t inadvertantly loading data that you don’t require.You should also be aware of circular dependency problems when using the default JSON serializer.