In the last three posts we looked at an implementation of extra-lazy Count for EF 4.1 and how to reduce the Reflection cost of this implementation. However, when looking at LazyCountCollection it is fairly apparent that the same pattern can be used for more than just extra-lazy Count. In this we’ll look at a more general implementation of ICollection<T> that contains an underlying IQueryable<T> that can be used for more than just extra-lazy Count.
Lazy loading of collections is the process whereby a collection of entities is automatically loaded from the database the first time that the collection property referring to the entities is accessed. Support for lazy loading was added to Entity Framework 4.0 and is described here for EF 4.1. EF Lazy loading works with (almost) any implementation of ICollection<T> and does not mess with that implementation.
Lazy loading is useful in that it doesn’t require all entities that an application might use to be eagerly loaded up-front and also doesn’t require special code to be written to explicitly load related entities when they are needed—you just access the collection and it is automatically loaded if needed.
For some people lazy loading doesn’t go far enough. In particular, it is not uncommon to want to know how many related entities exist without actually loading all those entities.