2

I know a lot has been said and posted about eager loading and lazy loading on NHibernate. I'v read all (lie!) the threads and posts and answers about why I should or should not use "lazy=false" while mapping or how to use HQL or Criteria to eager-load objects when I think is a good place to. Although, I haven't found anything about eager loading a collection property when I use the ISession.Get method. Let me explain the scenario:

I want to use a generic repository (base for all other specialized descendents classes), that would look like this:

class Repository<T>
{
  public T GetById(long id)
  {
    using (ISession session = NHibernateHelper.OpenSession())
    {
      return session.Get<T>(id);
    }
  }
}

My question is: is there any way to use the generic "GetById" method (just like above) and even so use eager loaded all objects loaded in it?

I know some will answer "just use NHibernateUtil.Initialize", but for that I have to "know" my entity and, in that case, I will have to override my method and lose the generic advantage of my Repository. The same can be said about using HQL or Criteria or whatever other way that not using the simplicity of "Get". Besides, I would like to have the other advantages of Get (or Load) methods (because of this).

Any idea? Did I lose something? Don't I have annnyyy idea of what I'm talking about (quite possible)?

Roger Kiihl
  • 115
  • 1
  • 13
  • simple- don't use a repository; rather, use the `ISession` object directly instead. here's why- http://ayende.com/blog/3955/repository-is-the-new-singleton – J. Ed Aug 30 '12 at 23:30
  • That's just the wrong usage pattern for a session. You shouldn't open and close a session within a repository, much less to return a single value. – Diego Mijelshon Aug 31 '12 at 01:10
  • See this: http://stackoverflow.com/questions/11420632/nhibernate-eager-loading-at-runtime it may lead you in the right direction. – znelson Aug 31 '12 at 04:00
  • @DiegoMijelshon: In a ntier application, at some point, one object of class Customer will be requested to ben shown to the user. That request will come of some point to the server, and the sever will have no other option but open a session, get the object and return it, right? – Roger Kiihl Aug 31 '12 at 11:57
  • 1
    Yes and no. Managing the session is the responsibility of an infrastructure layer (which depends on the application type), not the repository. – Diego Mijelshon Aug 31 '12 at 15:27

0 Answers0