1
votes

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.

2

2 Answers

2
votes

This is expected behaviour. When the JSON serializer comes to serialize the type, it will enumerate the LandUnits navigation 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 Include method) or explicly loading (using the Load method) 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.

0
votes

This just shows that you havent yet requested any of the LandUnits yet (if you loop through them using something like a foreach they will be loaded). So the JSON object is empty when using lazy loading.

When lazy loading is turned off, the LandUnits object is null as the LandUnits have not been loaded and cannot be loaded at a later time (attempting to do so would throw an error)