Hello,
I have been using NHibernate for some time and I am very satisfied with it. Recently I have come to a problem for which I couldn't find a solution. I have a User class with a collection of Accounts. I would like to build a query which would return all users (with their Accounts collection eagerly loaded), that have an account opened before some date.
The following query would work but it returns all users:
Code:
ISession session = factory.OpenSession();
IList<User> users = session.CreateCriteria(typeof(User))
.SetFetchMode("Accounts", FetchMode.Join)
.List<User>();
session.Close();
int accountsNumber = users[0].Accounts.Count; // works here but I don't know how to perform restrictions on the Accounts collection in my query.
The following works inside the session but once the session is closed I get a LazyInitializationException:
Code:
ISession session = factory.OpenSession();
IList<User> users = session.CreateCriteria(typeof(User))
.SetFetchMode("Accounts", FetchMode.Join)
.CreateAlias("Accounts", "a")
.Add(Expression.Le("a.OpenDate", date))
.List<User>();
session.Close();
int accountsNumber = users[0].Accounts.Count; // get LazyInitializationException here
From what I have seen so far, it seems that it is impossible to use SetFetchMode and CreateAlias on the same query, because CreateAlias always overrides the SetFetchMode behavior. If I define the Accounts collection as with lazy="false" in the mapping file, then everything works as expected, but I don't want to load the Accounts collection every time, only for this particular query. Is it possible to perform this query with HQL instead of using the criteria API? Can I eagerly load the collection and perform restrictions on it? A similar issue has been discused in this
post. To resolve the issue it was suggested to remove the CreateAlias and use a long notation, but I couldn't understand what this long notation would be. Any help would be greatly appreciated.
Regards,
Darin