Filtering collections

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 ...

Get NHibernate 4.x Cookbook - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.