Using detached queries
In some cases, it may be preferable to build an HQL or criteria query object in parts of your application without access to the NHibernate session and then execute them elsewhere with a session available. In this recipe, we'll show you how to use detached queries and criteria.
Getting ready
Complete the Getting Ready section at the beginning of this chapter.
How to do it…
Add a new folder named
DetachedQueries
to the project.Add a new class named
Recipe
to the folder:using NH4CookbookHelpers.Queries; using NH4CookbookHelpers.Queries.Model; using NHibernate; using NHibernate.Criterion; namespace QueryRecipes.DetachedQueries { public class Recipe : QueryRecipe { protected override void Run(ISession session) { var isbn = "3043"; var query = DetachedCriteria.For<Book>() .Add(Restrictions.Eq("ISBN", isbn)); var book = query.GetExecutableCriteria(session) .UniqueResult<Book>...