Query entities by ID
Loading a specific identified entity from the database is a very common operation in the majority of NHibernate applications. Just querying for an entity by its Id or primary key may seem like the obvious thing to do, but as we'll see in this recipe, there's a bit more to it.
Getting ready
Complete the Getting Ready section at the beginning of this chapter.
How to do it…
- Add a new folder named
QueryById
to the project. - Add a new class named
Recipe
to the folder, containing the following code:using NH4CookbookHelpers; using NH4CookbookHelpers.Queries.Model; using NHibernate; namespace QueryRecipes.QueryById { public class Recipe : QueryRecipe { protected override void Run(ISession session) { var product1 = session.Get<Product>(1); ShowNumberOfQueriesExecuted(); ShowProduct(product1); ShowNumberOfQueriesExecuted(); var product2 = session.Load<Product>(2); ...