NHibernate 3: Creating a Sample Application

Exclusive offer: get 50% off this eBook here
NHibernate 3 Beginner's Guide

NHibernate 3 Beginner's Guide — Save 50%

Rapidly retrieve data from your database into .NET objects

$26.99    $13.50
by Dr. Gabriel Nicolas Schenker | September 2011 | Open Source

In this article we will see how easy it is to use NHibernate in a real world application. We will create, with minimal effort, a fully working sample that allows us to write to and subsequently, read data from a database.

In this article by Dr. Gabriel Nicolas Schenker, author of NHibernate 3 Beginner’s Guide, we shall:

  • Prepare our system to enable development of applications using NHibernate
  • Create a simple model of a problem domain
  • Create a database and define a mapping between the model and the database
  • Write and read data to and from the database

 

(For more resources on NHibernate, see here.)

 

Prepare our development environment

We assume that you have a computer at hand which has Windows Vista, Windows 7, Windows Server 2003 or Windows Server 2008 installed. If you are using an Apple computer, then you can install, for example, Windows 7 as a virtual machine.

First, install Microsoft Visual Studio 2010 Professional, Microsoft Visual C# 2010 Express or Microsoft Visual Basic 2010 Express on your system. The Express editions of Visual Studio can be downloaded from http://www.microsoft.com/express/windows.

Note that NHibernate 3.x can also be used with the 2008 editions of Microsoft Visual Studio, but not with any older versions. NHibernate 3.x is based on the .NET framework version 3.5, and thus only works with IDEs that support this or a higher version of the .NET framework.

Additionally, note that if you don't want to use Visual Studio, then there are at least two other free OSS options available to you:

  • MonoDevelop is an IDE primarily designed for C# and other .NET languages. MonoDevelop makes it easy for developers to port .NET applications created with Visual Studio to Linux and to maintain a single code base for all platforms. MonoDevelop 2.4 or higher can be downloaded from http://monodevelop.com/download.
  • SharpDevelop is a free IDE for C#, VB.NET, and Boo projects on Microsoft's .NET platform. It is open source. SharpDevelop 3.2 or higher can be downloaded from http://sharpdevelop.net/OpenSource/SD/Default.aspx.

Furthermore, note that NHibernate also works on Mono: http://www.mono-project.com.

Next, we need a relational database to play with. NHibernate supports all major relational databases like Oracle, MS SQL Server, MySQL, and so on. We will use MS SQL Server as our Relational Database Management System (RDBMS).

Microsoft SQL Server is the most used RDBMS in conjunction with NHibernate and, in general, with .NET projects. The SQL Server driver for NHibernate is one of the most tested drivers in NHibernate's suite of unit tests, and when specific new features come out, it is likely that they will be first supported by this driver.

Install the free Microsoft SQL Server 2008 R2 Express on your system if you have not already done so during the install of Visual Studio. You can download the express edition of MS SQL Server from here http://www.microsoft.com/express/Database/. For our samples, it really doesn't matter which version you download: the 32-bit or the 64-bit version. Just take the one that matches best with the bitness of your operating system. Make sure that you install SQL Server with the default instance name of SQL Express.

Make sure you also download and install the free SQL Server Management Studio Express (SSMS) from the following link:

http://www.microsoft.com/download/en/details.aspx?id=22985

Now, we are ready to tackle NHibernate. We can download NHibernate 3.1.0 GA from Source Forge http://sourceforge.net/projects/nhibernate/. The download consists of a single ZIP file containing the following content, as shown in the screenshot:

NHibernate 3 Beginner’s Guide

The binaries that are always needed when developing an NHibernate based application can be found in the Required_Bins folder. Opening this folder, we find the files as shown in the following screenshot:

NHibernate 3 Beginner’s Guide

Note that if you are downloading version 3.1 or newer of NHibernate, you will no longer find the two DLLs, Antlr3.Runtime.dll and Remotion.Data.Linq.dll, in the ZIP file that were present in version 3.0. The reason is that they have been IL merged into the NHibernate.dll.

If we want to use lazy loading with NHibernate (and we surely will), then we also have to use some additional files which can be found in the Required_For_LazyLoading folder.

Lazy loading is a technique that is used to load certain parts of the data only when really needed, which is when the code accesses it.

There are three different options at hand. We want to choose Castle. The corresponding folder contains these files, as shown in the following screenshot:

NHibernate 3 Beginner’s Guide

As we are also using Fluent NHibernate, we want to download the corresponding binaries too. Go grab the binaries from the Fluent NHibernate website and copy them to the appropriate location on your system. In either case, there is no installer available or needed. We just have to copy a bunch of files to a folder we define. Please download Fluent NHibernate, which also contains the binaries for NHibernate, from here (http://fluentnhibernate.org/downloads), as shown in the following screenshot. Make sure you download the binaries for NHibernate 3.1 and not an earlier version.

NHibernate 3 Beginner’s Guide

Save the ZIP file you just downloaded to a location where you can easily find it for later usage. The ZIP file contains the files shown in the following screenshot:

NHibernate 3 Beginner’s Guide

The only additional files regarding the direct NHibernate download are the FluentNHibernate.* files. On the other hand, we do not have the XSD schema files (nhibernate-configuration.xsd and nhibernate-mapping.xsd) included in this package and we'll want to copy those from the NHibernate package when implementing our sample.

 

Defining a model

After we have successfully downloaded the necessary NHibernate and Fluent NHibernate files, we are ready to start implementing our first application using NHibernate. Let's first model the problem domain we want to create the application for. The domain for which we want to build our application is a product inventory system. With the application, we want to be able to manage a list of products for a small grocery store. The products shall be grouped by category. A category consists of a name and a short description. The product on the other hand has a name, a short description, a category, a unit price, a reorder level, and a flag to determine whether it is discontinued or not. To uniquely identify each category and product, they each have an ID. If we draw a class diagram of the model just described, then it would look similar to the following screenshot:

NHibernate 3 Beginner’s Guide

Unfortunately, the class designer used to create the preceding diagram is only available in the professional version of Visual Studio and not in the free Express editions.

 

Time for action – Creating the product inventory model

Let's implement the model for our simple product inventory system. First, we want to define a location on our system, where we will put all our code that we create.

  1. Create a folder called NH3BeginnersGuide on your file system. Inside this new folder, create another folder called lib. This is the place where we will put all the assemblies needed to develop an application using NHibernate and Fluent NHibernate.
  2. Locate the ZIP file containing the Fluent NHibernate files that you downloaded in the first section of this article. Extract all files to the lib folder created in the preceding step.
  3. Open Visual Studio and create a new project. Choose WPF Application as the project template. Call the project Chapter2. Make sure that the solution you create will be saved in the folder NH3BeginnersGuide you created in the preceding step. When using VS 2008 Pro, you can do this when creating the new project. If, on the other hand, you use the Express edition of Visual Studio, then you choose the location when you first save your project.

    (Move the mouse over the image to enlarge.)

  4. Add a new class to the project and call it Category. To this class, add a virtual (auto-) property called Id, which is of the int type. Also, add two other virtual properties of the string type, called Name and Description. The code should look similar to the following code snippet:

    namespace Chapter2
    {
    public class Category
    {
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
    public virtual string Description { get; set; }
    }
    }

    Downloading the example code
    You can download the example code files here.

  5. Add another class to the project and call it Product. To this class, add the properties, as shown in the following code snippet. The type of the respective property is given in parenthesis:
    Id (int), Name (string), Description (string), Category (Category), UnitPrice (decimal), ReorderLevel (int), and Discontinued (bool). The resulting code should look similar to the following code snippet:

    namespace Chapter2
    {
    public class Product
    {
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
    public virtual string Description { get; set; }
    public virtual Category Category { get; set; }
    public virtual decimal UnitPrice { get; set; }
    public virtual int ReorderLevel { get; set; }
    public virtual bool Discontinued { get; set; }
    }
    }

What just happened?

We have implemented the two classes Category and Product, which define our simple domain model. Each attribute of the entity is implemented as a virtual property of the class. To limit the amount of code necessary to define the entities, we use auto properties. Note that the properties are all declared as virtual. This is needed as NHibernate uses lazy loading by default.

 

NHibernate 3 Beginner's Guide Rapidly retrieve data from your database into .NET objects
Published: August 2011
eBook Price: $26.99
Book Price: $44.99
See more
Select your format and quantity:

 

(For more resources on NHibernate, see here.)

 

Mapping our model

Now that we have defined and implemented the model for our simple product inventory application, we need to instruct NHibernate how to map our model classes to the underlying tables in the database. The mapping is responsible to define which class maps to which table, and which property of a class maps to which column of a table. Having defined this information, NHibernate can successfully operate and create the necessary SQL statements that allow us to add, update, and delete data in the database, as well as query existing data.

Various methods exist to show how we can define the mappings. Probably, the most common methods are either to define the mappings in the form of XML documents or to define them in code.

 

Time for action – Creating the mapping classes

To make our life very simple, we will use Fluent NHibernate to map our model to the underlying database. Fluent NHibernate allows us to define the mapping in code, in a type-safe way.

  1. Add a reference to FluentNHibernate.dll and to NHibernate.dll, which you can locate in the lib folder, as shown in the following screenshot:

    NHibernate 3 Beginner’s Guide

  2. Add a new class to the project and call it CategoryMap. Add using FluentNHibernate.Mapping; to the file.
  3. Make the class inherit from ClassMap<Category>.
  4. Add a default constructor to the class and define the mapping for the Id.
  5. In the constructor, add Id(x =>x.Id);, that is, we use the Id method defined in the base class to define the mapping of Id. The Id method expects a lambda expression which identifies the property of the class Category, which shall be mapped as Id.
  6. Furthermore, in the constructor, add Map(x =>x.Name); to define the mapping for the Name property.
  7. Do the same thing for the Description property. The resulting code should look similar to the following code snippet:

    using FluentNHibernate.Mapping;
    namespace Chapter2
    {
    public class CategoryMap : ClassMap<Category>
    {
    public CategoryMap()
    {
    Id(x => x.Id);
    Map(x => x.Name);
    Map(x => x.Description);
    }
    }
    }

  8. Add another class called ProductMap to the project and add the same using statement to the file as in the CategoryMap file. Make the class inherit from ClassMap<Product> and also add a default constructor.
  9. In the default constructor, add code to map the property Id as the primary key.
  10. Furthermore, add code to map the properties: Name, Description, UnitPrice, ReorderLevel, and Discontinued.
  11. Finally, use References(x =>x.Category); to map the Category property. When done, your code should look similar to the following code snippet:

    using FluentNHibernate.Mapping;
    namespace Chapter2
    {
    public class ProductMap : ClassMap<Product>
    {
    public ProductMap()
    {
    Id(x => x.Id);
    Map(x => x.Name);
    Map(x => x.Description);
    Map(x => x.UnitPrice);
    Map(x => x.ReorderLevel);
    Map(x => x.Discontinued);
    References(x => x.Category);
    }
    }
    }

    Make sure all your classes (that is, Category, Product, CategoryMap, and ProductMap) are defined as public. If these classes are not defined as public, NHibernate will not be able to discover and use them.

What just happened?

We have defined two classes which provide NHibernate with detailed information about how the model classes Category and Product can be mapped to an underlying database containing two compatible tables for each Category and Product class, respectively. Looking at the code, it seems to be very little information that we provide to NHibernate to do its job, but the nice thing is that Fluent NHibernate uses a lot of predefined and meaningful defaults if not defined otherwise.

 

Creating the database schema

We have defined a model for our problem domain and have defined the necessary information that NHibernate needs to map the model to an underlying database. Now we need to create this database. However, we do not want to handcraft the database schema, but rather let NHibernate create the database schema for us. The only thing we need to do manually is create a new empty database.

NHibernate will use the meta information we provided via the definition of the mapping classes to create an appropriate database schema.

 

Time for action – Creating the database

First, we will manually create an empty new database and then we will add code to our application, which allows us to delete and recreate the database schema.

  1. Open the Microsoft SQL Server Management Studio (SSMS), which was installed as part of the MS SQL Server Express setup. When asked for the connection details, enter .\SQLExpress as the server name and choose Windows Authentication as the authentication mode. This is shown in the following screenshot:

    NHibernate 3 Beginner’s Guide

    If you are accessing your locally installed SQL Server Express edition, then you can also use the alias (local) instead of .\SQLExpress to connect to your database.

  2. Right-click on the Databases folder and select New Database.... Enter NH3BeginnersGuide as the database name and click on OK. A new empty database will be created for you.
  3. Back in Visual Studio, open the MainWindow.xaml file and modify XAML, as shown in the following code snippet, to create a window with the title Product Inventory displaying one button with the text "Create Database":

    <Window x:Class="Chapter2.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/
    2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Product Inventory" Height="350" Width="525">
    <Grid>
    <Grid.RowDefinitions>
    <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <Button x:Name="btnCreateDatabase"
    Content="Create Database"
    Click="btnCreateDatabase_Click"/>
    </Grid>
    </Window>

  4. Open the preceding code file of MainWindow (the MainWindow.xaml.cs file) and implement the code which defines a connection string to access our NH3BeginnerGuide database on SQL Server. This is shown in the following code snippet:

    const string connString = "server=.\\SQLExpress;" +
    "database=NH3BeginnersGuide;" +
    "Integrated Security=SSPI;";

  5. Add the following using statements at the top of the MainWindow.xaml.cs file:
    using FluentNHibernate.Cfg;
    using FluentNHibernate.Cfg.Db;
    using NHibernate.Cfg;
    using NHibernate.Tool.hbm2ddl;
  6. Use the Fluently class of Fluent NHibernate to define a configuration which will allow us to ask NHibernate to create the database schema via the CreateSchema method passed as a parameter to the ExposeConfiguration method:

    Fluently.Configure()
    .Database(MsSqlConfiguration
    .MsSql2008
    .ConnectionString(connString))
    .Mappings(m =>m.FluentMappings.
    AddFromAssemblyOf<ProductMap>())
    .ExposeConfiguration(CreateSchema)
    .BuildConfiguration();

  7. In the CreateSchema method, use the SchemaExport class of NHibernate to delete and create the schema based on the metadata available through the configuration files, as shown in the following code snippet:

    private static void CreateSchema(Configuration cfg)
    {
    var schemaExport = new SchemaExport(cfg);
    schemaExport.Drop(false, true);
    schemaExport.Create(false, true);
    }

  8. Putting all the preceding code together, MainWindow should look similar to the following code snippet:

    using System.Windows;
    using FluentNHibernate.Cfg;
    using FluentNHibernate.Cfg.Db;
    using NHibernate.Cfg;
    using NHibernate.Tool.hbm2ddl;
    namespace Chapter2
    {
    public partial class MainWindow
    {
    const string connString = "server=.\\SQLExpress;" +
    "database=NH3BeginnersGuide;" +
    "Integrated Security=SSPI;";
    publicMainWindow()
    {
    InitializeComponent();
    }
    private void btnCreateDatabase_Click(object sender,
    RoutedEventArgs e)
    {
    Fluently.Configure()
    .Database(MsSqlConfiguration
    .MsSql2008
    .ConnectionString(connString))
    .Mappings(m =>m.FluentMappings
    .AddFromAssemblyOf<ProductMap>())
    .ExposeConfiguration(CreateSchema)
    .BuildConfiguration();
    }
    private static void CreateSchema(Configuration cfg)
    {
    var schemaExport = new SchemaExport(cfg);
    schemaExport.Drop(false, true);
    schemaExport.Create(false, true);
    }
    }
    }

  9. Run the application and click on the Create Database button. Verify within SSMS that the database NH3BeginnersGuide now contains two tables called Category and Product, respectively. Furthermore, verify that the tables contain a column for each property of the respective class, as shown in the following screenshot:

    NHibernate 3 Beginner’s Guide

What just happened?

We have used SSMS to define an empty new SQL Server database. We then created a new WPF application with a single button on the main window. When we run the application, we can trigger code by clicking on the button which creates an NHibernate configuration object. This object is then used in conjunction with the SchemaExport class of NHibernate to create the database schema in the previously defined database.

 

Creating a session factory

To create sessions through which we can access the database, we need a session factory. Every session object that we ever need has to be created with the aid of such a session factory. Once again, we can use the classes provided by Fluent NHibernate to make things simple. We use the Fluently helper class to define, in a fluent way, the necessary information NHibernate needs to be able to create a session factory for us.

Specifically, we have to define what database product and which version of it we are going to use. We also have to define where Fluent NHibernate can find all the mapping files we have written. This leads us to the following code:

private ISessionFactory CreateSessionFactory()
{
return Fluently.Configure()
.Database(MsSqlConfiguration
.MsSql2008
.ConnectionString(connString))
.Mappings(m =>m.FluentMappings
.AddFromAssemblyOf<ProductMap>())
.BuildSessionFactory();
}

The preceding method creates a session factory for an MS SQL Server version 2008. It uses the settings of connString when connecting to the database. We further instruct Fluent NHibernate to parse the assembly in which ProductMap is implemented for any mapping classes. With all this information, we instruct NHibernate to create the factory by calling BuildSessionFactory().

 

Time for action – Creating a session factory

We now want to write the code necessary to create a session factory for our product inventory application.

  1. Add a reference NHibernate.ByteCode.Castle.dll to the project. This file can be found in the lib folder. NHibernate needs this assembly to create proxies.
  2. Add a using NHibernate statement to the preceding code of MainWindow (the MainWindow.xaml.cs file).
  3. Add a CreateSessionFactory method, as described above, to the preceding code.
  4. Extend the grid of MainWindow with another row with a height set to Auto.
  5. Add another button to the MainWindow and name it btnCreateSessionFactory and define its content as Create Session Factory. Set the Grid.Row to 1. Furthermore, define a click event handler for this new button. The definition of the Grid should look similar to this:

    <Grid>
    <Grid.RowDefinitions>
    <RowDefinition Height="Auto" />
    <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <Button x:Name="btnCreateDatabase"
    Content="Create Database"
    Click="btnCreateDatabase_Click"/>
    <Button x:Name="btnCreateSessionFactory"
    Content="Create Session Factory"
    Click="btnCreateSessionFactory_Click"
    Grid.Row="1"/>
    </Grid>

  6. In the click event handler for this new button, enter the following code:
    var factory = CreateSessionFactory();
  7. Start the application and test whether you can successfully create a session factory, as shown in the following screenshot:

    NHibernate 3 Beginner’s Guide

What just happened?

We have added a second button to the main window of our application. In the click event handler of this button, we have implemented the code that creates a new NHibernate session factory. We built the session factory with the aid of the Fluently helper class provided by Fluent NHibernate. The session factory can then be used to create session objects used to access the database created in the preceding exercise.

 

NHibernate 3 Beginner's Guide Rapidly retrieve data from your database into .NET objects
Published: August 2011
eBook Price: $26.99
Book Price: $44.99
See more
Select your format and quantity:

 

(For more resources on NHibernate, see here.)

 

Opening a session

Our application needs a session object to communicate with the database when writing or reading data. As mentioned above, session objects can only be obtained through a session factory. Once we have constructed a session factory, opening a session is a quick and cheap operation. After we have finished using our session object, we must not forget to close the session and dispose it. We can use a using statement to instruct the compiler to do this automatically for us.

 

Time for action – Opening a session to the database

We will implement the code such that our product inventory application can open a session to the database.

  1. Add another row to the grid of MainWindow. In this new third row, place an additional button called btnCreateSession with content Create Session. Furthermore, define an event handler for the click event. The code for the button should look similar to the following code snippet:

    <Button x:Name="btnCreateSession"
    Content="Create Session"
    Click="btnCreateSession_Click"
    Grid.Row="2"/>

  2. In the event handler of this button, add the following code:

    private void btnCreateSession_Click(object sender,
    RoutedEventArgs e)
    {
    var factory = CreateSessionFactory();
    using (var session = factory.OpenSession())
    {
    // do something with the session
    }
    }

  3. Start the application and verify that you can indeed open a session to the database.

What just happened?

We added yet another button to the main window of the application whose click event handler contains the code to first create a session factory by using the code implemented in the preceding exercise. This session factory is then used to open a session object. We have not yet done anything meaningful with this session object. To use the session will be part of the next exercise.

 

Persisting objects to the database

The whole ceremony of defining mappings, creating a database schema, creating a session factory, and finally creating and opening a session object has one single purpose: we want to persist the data created by our product inventory application to a durable data store.

Let's first create a new category object. We can do this by using the following code snippet:

var category = new Category
{
Name = "Beverages",
Description = "Some description"
};

Next, we want to save this new category object and we can do so by using the following code:

var id = session.Save(category);

The value that is returned from the save method corresponds to the ID of the newly created category object.

Now, let's create a product. The product has a reference to a category object. Before we can save a product, the corresponding category object must have been persisted to the database. The following code would work:

var category = new Category { Name = "Beverages" };
var product = new Product { Name = "Milk", Category = category };
session.Save(category);
session.Save(product);

The session object can also be used to delete an existing object from the database. The command to do so is as simple as the following code:

session.Delete(category);

Here, the category object we pass as a parameter to the delete method corresponds to the one we want to remove from the database.

 

Time for action – Adding a new category to the database

We want to add the possibility to add a new category to the main window of our application. For this we need two textboxes where the user can enter the category name and description, we also need a button to trigger the creation of the category.

  1. Add another row to the grid of the MainWindow; set the row height to *. This will be the fourth row so far. In this row, we define another grid called CategoryGrid, which will contain all the controls we need to create a new category. This new grid should look similar to the following code snippet:

    <Grid x:Name = "CategoryGrid" Grid.Row="3" Margin="0 10 0 0">
    <Grid.ColumnDefinitions>
    <ColumnDefinition Width="Auto"/>
    <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
    <RowDefinition Height="Auto" />
    <RowDefinition Height="Auto" />
    <RowDefinition Height="Auto" />
    <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <TextBlock Text="Category Name:"/>
    <TextBlock Text="Category Description:"
    Grid.Row="1"/>
    <TextBox x:Name="txtCategoryName"
    Grid.Row="0" Grid.Column="1"/>
    <TextBox x:Name="txtCategoryDescription"
    Grid.Row="1" Grid.Column="1"/>
    <Button x:Name="btnAddCategory"
    Content="Add Category"
    Grid.Row="2"
    Click="btnAddCategory_Click" />
    </Grid>

  2. In the preceding code file of MainWindow, add the following code to the click event handler of the new button:

    private void btnAddCategory_Click(object sender,
    RoutedEventArgs e)
    {
    var factory = CreateSessionFactory();
    using (var session = factory.OpenSession())
    {
    var category = new Category
    {
    Name = txtCategoryName.Text,
    Description = txtCategoryDescription.Text
    };
    session.Save(category);
    }
    }

  3. Start the application and try to add several new categories to the database. Use SSMS to verify that the categories are indeed added to the Category table, as shown in the following screenshot:

    NHibernate 3 Beginner’s Guide

What just happened?

In this exercise, we extended our main window to be able to enter a name and description for a category, which we can then store in the database by clicking on the Add Category button, which we also added to the window. In the click event handler of the Add Category button, we implemented a code to open an NHibernate session object, create a new Category entity from the values entered by the user into the Name and Description textboxes, and then, using the session object, save the category to the database.

 

Reading from the database

Persisting data into a database is surely important, but we also want to be able to reuse this data and thus must have a means to access it. The NHibernate session object provides us with this possibility. We can use the session object directly to access a single object in the database, which is identified by its primary key by using the following code:

var category = session.Get<Category>(1);

NHibernate will query the database for a category record in the category table having an ID of 1. NHibernate will then take this data and create a category object from it. We also say, "NHibernate rehydrates an object".

If we want to read not only a single object, but a list of objects from the database, we can use the LINQ to NHibernate provider to do so. The following statement will read all records from the category table and generate a list of the category objects out of it:

var categories = session.Query<Category>();

We can even go a step further and, for example, query a list of all discontinued products sorted by their name with the following statement:

var products = session.Query<Product>()
.Where(p =>p.Discontinued)
.OrderBy(p =>p.Name);

 

Time for action – Loading the list of all categories from the database

We want to add a list box to our application where we can display the list of all the categories that have been added to the database so far.

  1. Add another row to the CategoryGrid. In the first column of the new row, add a command button which we will use to trigger the loading of the category list. In the second column, we need to add a list box which will be used to display the list of the retrieved categories. The XAML fragment for the button and the list box should look similar to the following code snippet:

    <Button x:Name="btnLoadCategories"
    Content="Load Categories"
    Grid.Row="3" VerticalAlignment="Top"
    Click="btnLoadCategories_Click" />
    <ListBox x:Name="lstCategories"
    Grid.Row="3" Grid.Column="1"/>

  2. Add a using NHibernate.Linq and using System.Linq statement to the top of the file.
  3. Now, add a code that creates a session factory, opens a new session, and loads the ordered list of categories to the click event handler of the new button. Take the list of categories and bind it to the list box. Your code should look similar to the following code snippet:

    private void btnLoadCategories_Click(object sender,
    RoutedEventArgs e)
    {
    var factory = CreateSessionFactory();
    using (var session = factory.OpenSession())
    {
    var categories = session.Query<Category>()
    .OrderBy(c =>c.Name)
    .ToList();
    lstCategories.ItemsSource = categories;
    lstCategories.DisplayMemberPath = "Name";
    }
    }

  4. Run the application and try to load the list of categories. Add more categories and then reload the list. Verify that all categories are loaded and that they are sorted by name in ascending order, as shown in the following screenshot:

    NHibernate 3 Beginner’s Guide

What just happened?

We added another button, called Load Categories, to the main window. The code we implemented in the click event handler of this latest button opens a session object and uses a LINQ query to retrieve a list of all the categories stored so far in the database. The list is ordered by the category name and displayed in a list box, which we also added to the main window.

Summary

We learned in this article what the minimal steps are that are needed to create a working application which uses NHibernate as an ORM framework, and is able to write data to and read data from a database. Specifically, we covered:

  • What the prerequisites are and how we need to configure our system to be able to develop applications that use NHibernate 3
  • How we can define a model and map this model to the underlying database by using Fluent NHibernate
  • How to make NHibernate automatically create a database schema for us
  • How we create a session factory and how to use this factory to create sessions, which in turn are used to persist data to and retrieve the existing data from the database

Further resources on this subject:


About the Author :


Dr. Gabriel Nicolas Schenker

Gabriel N. Schenker started his career as a physicist. Following his passion and interest in stars and the universe he chose to write his Ph.D. thesis in astrophysics. Soon after this he dedicated all his time to his second passion, writing and architecting software. Gabriel has since been working for over 12 years as an independent consultant, trainer, and mentor mainly on the .NET platform. He is currently working as chief software architect in a mid-size US company based in Austin TX providing software and services to the pharmaceutical industry as well as to many well-known hospitals and universities throughout the US and in many other countries around the world. Gabriel is passionate about software development and tries to make the life of developers easier by providing guidelines and frameworks to reduce friction in the software development process.

He has used NHibernate in many different commercial projects, web-based as well as Windows-based solutions. Gabriel has written many articles and blog posts about different aspects of NHibernate. He is the author behind the well-known NHibernate FAQ blog. Gabriel has also been a reviewer for the bestselling NHibernate 3 Cookbook.

Gabriel is married and father of four children and during his spare time likes hiking in the mountains, cooking and reading.

Books From Packt


NHibernate 3.0 Cookbook
NHibernate 3.0 Cookbook

NHibernate 2 Beginner's Guide
NHibernate 2 Beginner's Guide

ASP.NET jQuery Cookbook
ASP.NET jQuery Cookbook

.NET Compact Framework 3.5 Data Driven Applications
.NET Compact Framework 3.5 Data Driven Applications

ASP.NET MVC 2 Cookbook
ASP.NET MVC 2 Cookbook

.NET Generics 4.0 Beginner’s Guide
.NET Generics 4.0 Beginner’s Guide

ASP.NET 4 Social Networking
ASP.NET 4 Social Networking

Amazon Web Services: Migrating your .NET Enterprise Application
Amazon Web Services: Migrating your .NET Enterprise Application


Your rating: None Average: 5 (1 vote)

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Q
S
Q
5
G
G
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software