I have been following Rob Conery’s posts on the MVC Storefront, and trying the repository/pipes-filters for data access that he has been using.
While trying out the implementation of a LazyList he was using, I had noticed that the example table was being joined onto the category table. At the time however, I really had not thought much of it, until I read MVC Storefront: Brainbender Intermission which got me thinking.
Admittedly, I don’t really have to much of a problem with it loading all of the examples for all the categories at one time at the moment. However, I figured it would be nice to have it work the way intended, and query the database for the examples in a category only when asked for.
I liked the idea of the LazyList, and since I was already using a Service class for all data access, along with setting up the category hierarchy I moved the creation of the LazyList of examples property into the the GetCategories method of the service class.
It seems that as long as the LazyList is created after the categories .ToList() call it properly works. So I ended up with this code:
categories.ForEach(category => { category.Examples = new LazyList <DevExamples.Data.Example>( from e in repository.GetExamples() where e.CategoryId == category.ID select e); var subCategories = (from sub in categories where sub.ParentId == category.ID select sub).ToList(); category.SubCategories = subCategories; subCategories.ForEach(c => c.Parent = category); });