views:

24

answers:

1

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;
        }
A: 

Once you've closed the session (which happens at the end of your using block, 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)

Diego Mijelshon
So where should I open and close my sessions then? At the service layer? I don't really fancy passing a session object into every function and you can only have one session open at once so It wouldn't work very well if i passed in at the declaration of the repo when using multiple repo's would it?
Andi
@Diego Mijelshon Can you explain this a little more?
Pino
The repositories should be initialized with the SessionFactory, and use `GetCurrentSession()` to obtain a session. Binding/Unbinding a current session can be done on BeginRequest/EndRequest in a web app, for example.
Diego Mijelshon