Using lazy=”true” in my classes causes my application to work perfectly, but the performance is horrible. I turned this on back when I was creating this from a tutorial and just wanted to get something working as quickly as possible. (I used this tutorial: http://geekswithblogs.net/BobPalmer/archive/2010/04/23/mapping-object-relationships—quickstart-with-nhibernate-part-3.aspx which was very helpful at getting something that worked quickly)
I don’t need it to load all of these many-to-one classes when I just need to use the one object, so it made sense to turn lazy loading back on. Then, I looked into the objects and saw nothing but exceptions for those many-to-one classes inside my main objects. When I try to use those properties later I get the following error:
"Could not initialize proxy - no Session."
I’m guessing this means that the session is closed, so it fails when trying to lazy-load the additional objects. My session provider looks like this (same as the tutorial):
class SessionProvider {
private static ISessionFactory _sessionFactory;
private static Configuration _config;
public static ISessionFactory SessionFactory {
get {
if (_sessionFactory == null) {
_sessionFactory = Config.BuildSessionFactory();
}
return _sessionFactory;
}
}
private static Configuration Config {
get {
if (_config == null) {
_config = new Configuration();
_config.AddAssembly(Assembly.GetCallingAssembly());
}
return _config;
}
}
}
Which is then used by my repositories like this:
using (var session = GetSession()) { ... }
Which gets the session from this function:
private static ISession GetSession() {
return SessionProvider.SessionFactory.OpenSession();
}
So my question is, what am I expected to do here? Keep the session open? Make it static across all repositories? I don’t have enough experience with NHibernate to understand how this works yet. My priority right now is only reading from the database, if that makes any difference. This is going in a code library that will eventually be used both on our website and various C# .Net apps.
The recommended approach is to use the unit of work pattern. Another option for you would be to use eager loading if you know you’re going to need specific entities up front.