Chapter 4. Queries

In this chapter, we will cover the following recipes:

  • Query entities by ID
  • Using LINQ to NHibernate
  • Using CriteriaQueries
  • Using QueryOver
  • Using QueryOver projections and aggregates
  • Using the Hibernate Query Language
  • Using native SQL
  • Eager loading with LINQ
  • Eager loading with Criteria
  • Eager loading with QueryOver
  • Eager loading with HQL
  • Eager loading with SQL
  • Using named queries
  • Using detached queries
  • Using HQL for bulk data changes
  • Filtering collections
  • Using result transformers
  • Extra lazy collections

Introduction

Since all the recipes in this chapter deal with querying, we have provided the necessary setup and data using the NH4CookbookHelpers library. You can easily adapt the recipes to your own liking, but if you want to only test the queries, the supplied setup will work just fine.

Getting ready

  1. Create a new Windows Forms project named QueryRecipes in Visual Studio.
  2. Add a reference to NHibernate using NuGet Packet Manager Console:
    Install-Package NHibernate
    
  3. Also, add a reference to NH4CookbookHelpers.
  4. Remove the class Form1.cs from the project.
  5. Add using NH4CookbookHelpers; to the top of Program.cs.
  6. Edit Program.cs so that the last line in Main reads:
    Application.Run(new WindowsFormsRunner());

If you use NH4CookbookHelpers, you don't even have to have a database server available, since it uses an in-memory SQLite database by default. If you want to use something else, like a local SQL Server, you can specify a Configuration instance to be used. Perhaps the most convenient way is to use a coded configuration, as described in Chapter 1, The Configuration and Schema.

Somewhere prior to the last line in Main, specify a default configuration, as shown:

RecipeLoader.DefaultConfiguration = () => new Configuration()
.DataBaseIntegration(db =>
{
    db.Dialect<MsSql2012Dialect>();
    db.Driver<Sql2008ClientDriver>();
    db.ConnectionString =
      "Server=.SQLEXPRESS;Database=NHCookbook;Trusted_Connection=True;";
});

Please be advised that the database used in the recipes will be tinkered with, so don't use a database with data that you need to stay intact.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.249.174