Lazy loading

When you execute a query, Entity Framework only loads the data you explicitly request. Just because a Recipe has Ingredients or RecipeSteps, it doesn’t assume that you’re going to want that data, so it doesn’t fetch it. So what happens if you ask for something that hasn’t been loaded by the query?

LAZY LOADING (technically called IMPLICIT DEFERRED LOADING) is loading data only when and if you need it. It lets you do things like reference the ingredients of a recipe even when you haven’t loaded them.

In Entity Framework, lazy loading is controlled by setting the LazyLoadingEnabled property on the context, but the property is exposed in different places depending on which API you use:

In the objectcontext API

Image

In the dbcontext API

Image

Unfortunately, the defaults are inconsistent. For historical reasons, LazyLoadingEnabled is false by default for the ObjectContext, but if you use the Entity Model Designer to create your code, the default templates will set it to true. So—false if you do it yourself, true if you use a tool. LazyLoadingEnabled is true by default for the DbContext, and the tools leave it alone.

What’s a poor programmer to do? I think best practice is to always set it explicitly when you instantiate the context. That way you know.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset