Tuesday, April 20, 2010

ActiveRecord Lazy Initialization

I enabled lazy initialization by using the [Lazy=true] attribute on my Castle ActiveRecord classes, but I noticed that my application was being severely slowed down (by 30 seconds or so) when using a PaginationHelper combined with a FindAll on the class.  I figured that lazy initialization on the activerecord class would mean that none of the objects would be fully loaded except for the ones that were presented in the paginated view, which was 20.  Well, it turns out that I was wrong because of a "feature" I didn't find documented in ActiveRecord.

Apparently, any collections that are done using at least the [HasMany] attribute in an active record class must be separately defined as lazy in order to get a truly lazy initialized class.  As soon as I added Lazy=true to the HasMany attribute, I found that the pages loaded within a second or so, and problem solved!  Just to be sure, I added Lazy=FetchWhen.OnInvoke to the reverse class with the [BelongsTo] attribute, but depending on the implementation this may not be needed.