Hello,
We're using NHibernate 1.2.0beta2 in a WinForms application. The problem I'm going to talk about is the initialization of lazy-loaded collections.
About those collections, there are 3 possibilities when we're trying to access it:
a) the collection is initialized
b) the collection is not initialized, but the object holding the collection is still bound to a (open) session
c) the collection is not initialized and the object holding the collection is no longer bound to a session
Of course (a) is not a problem, everything works fine.
(b) is somewhat a problem, because there's no way to know that the object is still associated to a session.
(c) is a serious problem, because as far as I know, there's no way to know if the collection can be initialized or if the object has to be reassociated to an open session. And trying to reassociate the object with a new session, while there's another open session associated to it, results in an exception.
So for now, we're solving the problem this way:
Code:
public virtual void InitializeFieldCollection()
{
if (!NHibernateUtil.IsInitialized(this.FieldCollection))
{
try
{
NHibernateUtil.Initialize(this.FieldCollection);
}
catch
{
// not associated to an open session
using (Session session = DataStore.CreateSession())
{
session.Lock(this);
NHibernateUtil.Initialize(this.FieldCollection);
}
}
}
}
(in the above code, Session acts as a wrapper around an ISession-object)
Although it works, I don't like this approach: the try-catch is not very readable and looks messy. Also: Lock() may only be used on unmodified instances, which I'm not sure of at the moment I use it.
So my question is twofold:
- is there any way to know if an object is still associated to an open session ?
- is there a better way to solve this problem, comparing the method we're using above ?
I thought maybe a new method NHibernateUtil.CanInitialize() might help.