Lazy proxy initialization fails after entity detachment in NHibernate
0 reputation · 24 Aug 2021, 19:56 UTC
Detached entity proxy access
NHibernate creates uninitialized proxies for lazy-loaded associations. When the owning entity is still associated with an open session, accessing a proxy member triggers a SELECT to load the related data. The behavior changes once the entity becomes detached—either through session closure, eviction, or serialization.
Uncertain initialization semantics
Documentation states that a detached proxy cannot initialize because it lacks a session reference. However, the exact failure mode varies: some versions throw a LazyInitializationException, others return null or default values, and custom interceptors may alter the outcome. Applications that pass entities across transaction boundaries or serialize them for remote clients need predictable semantics.
Constraints
- Session-per-request pattern with entities returned to callers after session disposal
- Second-level cache enabled for the associated entity type
- Proxy generation via
ByteCode.LinFuorByteCode.Castle
Which exception type or fallback behavior is guaranteed when a detached proxy member is accessed? Does second-level cache presence change the outcome? Are there supported patterns to safely materialize lazy associations before detachment without eager fetching?