Loading related object in MVC can be pretty confusing.
There are lots of terms you need to be aware of and learn if you really want to know what you\'re doing when w
Lazy loading
Brand
is a POCO (plain old CLR object). It is persistence ignorant. In other words: it does not know it is created by an Entity Framework data layer. It knows even less how to load its Manufacturer
.
Still, when you do this
var brand = db.Brands.Find(1);
var manufacturer = brand.Manufacturer;
the Manufacturer
is loaded on the fly ("lazily"). If you monitor the SQL that's sent to the database you'll see that a second query is emitted to fetch the Manufacturer
.
That is because under the hood, EF does not create a Brand
instance, but a derived type, a proxy, that's stuffed with wiring to execute lazy loading. That's why the virtual
modifier is required for lazy loading to be enabled: the proxy must be able to override it.
Lazy loading is typically used in smart client applications where a context has a relatively long life span (e.g. context per form). Although I must say that even in smart client applications using short-lived contexts is beneficial and perfectly possible.
Eager loading
Eager loading means that you load an object with adhering objects (parents and/or children) in one take. That's what the Include
method is for. In the example
db.Brands.Include(b => b.Manufacturer)
you'll see that EF creates a SQL query with a join and that accessing a Brand
's Manufacturer
does not spawn a separate query any more.
Eager loading is the way to go in most situations (esp. in disconnected scenarios), because the recommended way to deal with context instances is to use them and dispose them for each unit of work. Thus, lazy loading is not an option, because for a navigation property to be lazy loaded the context must be alive.