I have some legacy code that does lots of lazy-loading of lots of "static" records, and produces a lot of N+1 alerts in NHibernate Profiler, which I'm trying to fix. I've found that by configuring second-level cache, it fixes many of the N+1s, but many still persist due to the entities being accessed by something other than their IDs i.e. a foreign key value on a child entity referring back to its parent as opposed to the child entity's primary key. My understanding is that second-level cache is only used when entities are accessed by their ID. I'm trying to eliminate as many N+1 issues as possible while minimizing code changes in the legacy code as much as possible.
Is there a way to short-circuit lazy loading in NHibernate such that custom code would be exercised prior to invoking NHibernate's lazy loading code to exercise a database query? Something like the following?
public class Customer
{
public virtual IList<SomeStaticData> Foo
{
get
{
return CachedStuff.GetStaticData() ?? InvokeNHibernateLazyLoad();
}
set;
}