ORM Lazy Loading Pitfalls
Object-relational mappers furnish a mapping layer between object-oriented code and relational databases. ORMs such as NHibernate and Entity Framework support lazy loaded associations which allow the loading of specific subsets of an object graph from an underlying relational store. This is beneficial because an object model can construct an object graph which is unfeasible to contain in main memory in its entirety. Lazy loading can prevent unnecessary data from being loaded and as such it is often presented as a performance optimization technique. This technique however incurs several drawbacks and is limited in its scalability. One drawback is that classes are static declarations and object associations will be accessible regardless of whether they are lazy loaded or eager loaded. As a result, it becomes more difficult to understand code because it isn’t immediately certain whether navigating an association will result in a database call behind the scenes. Moreover, care must be taken to ensure that an ORM session is available lest we run into the dreaded LazyInitializationException. Given that lazy loading is typically implemented using the proxy pattern, data access implementation details inevitably and invisibly leak into the rest of the application. In sense these characteristics can be regarded as a violation of the principle of least astonishment.
Read on →