-1

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;
}
Andy
  • 2,709
  • 5
  • 37
  • 64

1 Answers1

0

I think it is best to take a look at this answer here, https://stackoverflow.com/a/27164913/13945347 and then check out this article by Ayende Rahien to get a better understanding of what the N+1 problem really is, https://ayende.com/blog/3732/solving-the-select-n-1-problem.

I don't think the best solution to your problem is to approach it in the way you suggest. You should not short circuit the LazyLoad and should design your application and models with that in mind. Explicitly define which models should be eagerly fetched and which should be lazy loaded.