I have just converted my application from LINQ2SQL to NHibernate and I’m trying to figure out how to optimise the following example. I tried using the .Future method but when my session closes the view then tries to fetch the data and I get a session closed error.
Does anyone know any best practises for this kind of thing? I have a lot of scenario’s where I call a method within LINQ which gets data using NHibernate but I don’t want to return loads of data that isn’t required.
Method to get all books:
public IEnumerable<Book>GetAllBooks()
{
try
{
using (ISession session = NHibernateHelper.OpenSession())
{
return session.CreateCriteria<Widget>().ToList<Book>();
}
}
catch (Exception ex)
{
//Error stuff here
}
}
Method that then extends that functionality
public IEnumerable<Book> GetDefaultBookReadingList()
{
return from p in GetAllBooks()
where p.IsDefault
select p;
}
Once you’ve closed the session (which happens at the end of your
usingblock, you won’t be able to retrieve any lazy-loaded data.Depending on the application type, session management will be different, but a repository should NEVER open and close sessions.
In web applications, the most common pattern is session-per-request.
In windows applications, it can be conversation-per-business-transaction or, in simpler implementations, session-per-view(model)