Lazy Property Loading In NHibernate
Well, I am not going to give the implementation here, but here are some notes for the implementation. What you basically need is actually quite simple.
- Start with a partial query, as shown here.
- Instead of returning the object, return a proxy to the object, that is aware of which properties were loaded.
- When a property is accessed that is not in the loaded properties list, do the following:
- Load the real object using NHibernate.
- Copy the existing values from the current object to the newly loaded one. (Preserving state)
- Redirect all calls to the newly loaded object.
The whole thing is quite simple, once you think about it from the right angle. Then again, here talks the guy who spent two hours debugging why calling the wrong machine would fail.
Yup, that´s exactly how NPersist does it! :-)
More senseless blathering:
I was wondering what if the properties are set to lazy initialization in the proxy, as are the collections? Then the partial query would only load the given properties in the select clause.
I guess your steps are more reliable indeed