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…

  1. Add a new folder named QueryById to the project.
  2. 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); ...

Get NHibernate 4.x Cookbook - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.