In our model with Movies and ActorRoles
, we may eventually have movies with hundreds of actors. If we want to display a movie and show all the roles played by Harrison Ford, we certainly can:
foreach (var actorRole in movie.Actors .Where(x=>x.Actor=="Harrison Ford")) { Console.WriteLine("Harrison Ford played {0} in {1}", actorRole.Role, movie.Name); }
While that would work fine in small data sets, there's a risk that we will load a lot more data than necessary, just to show a couple of roles. What happens is that as soon as we're using the Actors property on each Movie
instance, we trigger the lazy loading mechanism and a query will be executed to fetch all ActorRoles
of that movie. The Where
expression specified doesn't affect this behavior, since it's effectively executed in memory.
For scenarios like this, NHibernate offers a function where an uninitialized (not yet loaded from database) collection can be filtered and...