0

Can I prevent nhibernate creating new ISessions when lazy loading? How?

Correction: I mean new IDbConnections. I have implemented my own DriverConnectionProvider and I see it gets called due to lazy loading

Stig
  • 1,974
  • 2
  • 23
  • 50

2 Answers2

3

NHibernate does not create any ISession by its initiative. Please post some example in which you feel this happen. The underlying connection is actually opened during a lazy fetch just because NH needs to connect to the database in order to fill lazy collections/associations.

Felice Pollano
  • 32,832
  • 9
  • 75
  • 115
  • Sorry I mean new IDbConnections. I have implemented my own DriverConnectionProvider and I see it gets called due to lazy loading. – Stig Mar 12 '11 at 12:33
0

If you are using NHibernate as a connection manager and sql generator. I.e. you have a lot of code like the following:

public IList<Entity> GetEntities()
{
    using (ISession session = CreateNewSession())
    {
        return session.List<Entity>();
    }
}

Then you cannot use lazy loading. So you will need to disable lazy loading. This can be most easily achieved by specifying default-lazy="false" on your hibernate-mapping tag http://nhibernate.info/doc/nh/en/index.html#mapping-declaration-mapping

I might recommend using an IStatelessSession instead of the default ISession as well. Keep in mind that this is not the recommended use of NHibernate.

Owen Pauling
  • 11,349
  • 20
  • 53
  • 64
Vadim
  • 17,897
  • 4
  • 38
  • 62