Archive for the ‘newbie’ Category

Howdy folks,

And welcome back to part 2 of our newbie nhibernate tutorial series. Here is a quick summary of what we did the last time, in part 1:

  • Create a basic database (w/ 1 table)
  • Create a new console application
  • Add the nhibernate binary files as references to our application

2.1 Creating the Entity Class

So far, so good. This time we will proceed with mapping our first table into a .NET class:

  1. Open the DevJour1 project we created the last time
  2. Add a new class to our project (right-click the project -> Add -> Class).
  3. Name it Book
  4. Add the properties as in the snippet below:


Figure 1: This class will reflect our table Book as of SQL Server DevJour database we created in part 1 of the tutorial series. Each field of the table Book will be mapped accordingly to the class’ property with the same name.

2.2 Creating the Mapping File

The mapping file is an XML document which tells nhibernate which DB field belongs to which property in the class, which type it has and many more things. Let’s dig right in:

1. Create and XML document (right-click on project -> Add new item -> XML file)

2. Name the XML file Book.hbm.xml and click on “Add” (Figure 2)

3. Important: Under Book.hbm.xml file’s properties, under Build Action, choose Embedded Resource. It will not work if you do not choose this type! (Figure 3)

4. Write the code for the mapping file according to Figure 4


Figure 2: Adding the mapping file. The .hbm. middle part of the file name stands for hibernate mapping.


Figure 3: Set the Build Action to Embedded Resource!


Figure 4: The mapping file Book.hbm.xml

2.3 Explanation of the Mapping File (Figure 4, line by line):

2: Specifying that this is a mapping file

3: Specifying the class and the table we are mapping from. Please note that it is required to enter the fully qualified class name followed by a comma, and then add the assembly name. The assembly name can be found by right-clicking on the project -> Properties ->Assembly name. This is important, too! Don’t worry about the lazy=true attribute, we’ll take care of that later.

4-6: Indicates that the PK id of the rows in the table belongs to the property Id of class Book. The generator tag just tells nhibernate that we are going to use our DBs unique id generator by default for creating new rows. This will be used once we create an object and save it to DB.

7-8: Property mappings. Where name attribute indicates the property’s name we’re mapping towards, and column attribute indicates the DB column we’re mapping from.

This is it already. Now we’ll head on to the final part of this issue: Crea

2.4 Creating the Configuration File

The purpose of creating this file is that we need to establish a connection to our database, hence we must provide driver, DB name, login credentials etc. for nhibernate.

Right-click on the project, go to Add new item -> Application Configuration File. Leave the name as it is (App.config, see Figure 5)

The newly created file looks like in Figure 6.


Figure 5: Creating the application configuration file.


Figure 6: The empty App.config

Now, let’s complete the App.config’s code:

   1: <?xml version="1.0"?>


   3: <configuration>


   5:     <configSections>

   6:         <section name="hibernate-configuration"

   7:                  type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate"/>

   8:     </configSections>


  10:     <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">

  11:         <session-factory>


  13:             <property name="connection.provider">

  14:                 NHibernate.Connection.DriverConnectionProvider

  15:             </property>


  17:             <property name="connection.driver_class">

  18:                 NHibernate.Driver.SqlClientDriver

  19:             </property>


  21:             <property name="connection.connection_string">

  22:                 Data Source=.\SQLEXPRESS;

  23:                                 AttachDbFilename=C:\PathToYourDbFile\devjour.mdf;

  24:                                 Integrated Security=True;

  25:                                 Connect Timeout=30;

  26:                                 User Instance=True

  27:             </property>


  29:             <property name="dialect">

  30:                 NHibernate.Dialect.MsSql2005Dialect

  31:             </property>


  33:             <property name="proxyfactory.factory_class">

  34:                 NHibernate.ByteCode.Castle.ProxyFactoryFactory,

  35:                 NHibernate.ByteCode.Castle

  36:             </property>


  38:         </session-factory>


  40:     </hibernate-configuration>

  41:     <startup>

  42:         <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>

  43:     </startup>

  44: </configuration>


Snippet 1: The configuration file.

As you can see, the App.config sections specify mostly the database connection modality, i.e. which driver to use, which connection provider, as well as the connection string.

Important: You do not have to write the connection string manually, but can simply copy it from the database explorer. There you simply right-click your database file, choose Properties, and copy the connection string from the corresponding field. In the example, I only split it up by semicolons in order to make it more readable; however: You should leave it as a one-liner.

Now, let’s write the Program class:

   1: using System;


   3: using System.Collections.Generic;


   5: using System.Linq;


   7: using System.Text;


   9: using NHibernate;


  11: using NHibernate.Cfg;


  13: using System.Reflection;


  15: namespace DevJour1

  16: {

  17:     class Program

  18:     {

  19:         static ISessionFactory s;

  20:         static void Main(string[] args)

  21:         {

  22:             Book b = new Book();

  23:             b.Title = "Pulse";

  24:             b.Author = "King";

  25:             ISession session = OpenSession();


  27:             try

  28:             {

  29:                 session.Save(b);

  30:                 Console.WriteLine(b.Title + "was successfully saved to DB.");

  31:             }

  32:             catch (Exception e)

  33:             {

  34:                 Console.WriteLine(e.Message);

  35:             }

  36:         }


  38:         static ISession OpenSession()

  39:         {

  40:             if (s == null)

  41:             {

  42:                 Configuration configuration = new Configuration();

  43:                 configuration.AddAssembly(Assembly.GetCallingAssembly());

  44:                 s= configuration.BuildSessionFactory();

  45:             }

  46:             return s.OpenSession();

  47:         }

  48:     }

  49: }


Snippet 2: Usage of our mapped entity. In this case, it is used for making an object of class Book persistent to the database.

2.5 Explanation of the Program class (snippet 2, line by line)

Premise: In order to execute queries, insertions (as in Snippet 1, the session’s Save method), updates or deletes, we need an object of which implements the  ISession interface. ISession is part of the nhibernate API, and the OpenSession() method simply returns an instance of such, w.r.t. the current assembly that we are working from.

21-24: Construct a new object of type Book and set its properties manually

25: Retrieve the ISession by calling OpenSession()

27-36: Calling the Save method and passing Book b as parameter. We perform some basic exception handling to see whether we did everything correctly. If no exception is thrown, we are fine.

That was already the essence of this code. We just created a .NET object and saved it to our database. In fact, we did so only about 50 lines of code (and another 45 for the mapping file).

Quite simple, wasn’t it?

Next time, in part 3, we’ll have a look on how to query the objects from DB and at the different ways we can execute queries.

Stay tuned for more nhibernate parts!

Best regards,


Read Full Post »

Hello all,

Want to make your life developing with nhibernate easier? Then, especially if you’re just getting started, you might want to have some IntelliSense support to ease the creation/modification of the .hbm.xml mapping files.

It’s quite simple:

1. Find the XML schema directory of your VS2010 Express (Beta 2, at this time) installation
Tools->Options will point you to the right place. Do not forget to select the Show all settings checkbox at the left bottom of the window:


2. Then, go to the folder you extracted the nhibernate binaries into. Go into the subfolder Required_Bins and copy the two .xsd files nhibernate-configuration.xsd and nhibernate-mapping.xsd


3. Copy them into the XMLSchemas folder you found in step 1

That’s all there is to it!

Without restarting VS2010 Express, the IDE’s IntelliSense will support you from now on with the mapping file’s tags and attributes (show available tags/attributes, help w/ code completion etc.)

Especially in the beginning of your O/R mapping career this will save you a great deal of time and nerves.

Enjoy and check back soon, for there is more to come!


Read Full Post »

Hello all,

Before we actually start, let’s give a brief outline of the tools we use for the O/R mapping:

Important: When installing VS2010 Express Beta, you will be asked whether or not to install SQL Server Express 2008 SP1. Do that.

Extract the NHibernate binaries to a local directory.

1.1 Preparing the DB

Before we actually start mapping database records to objects, we need to have what? Correct, a database! So we simply create our own database. The purpose of this tutorial is not to show how to create a DB, so I put it simply as a series of screenshots with captions:


Figure 1: The Database Explorer of Visual C# Express is a tool for exploring and modifying databases. If not shown upon VS C# startup, simply hit [CTRL + W, L] to display it. Here, right-click on “Data connections”, and subsequently on “Add connection”.


Figure 2: We will create a DB and store it in a file. Select as shown on the screenshot and proceed with “Continue”.


Figure 3: Only field to concern is Database file name. Enter a new file name or choose an existing one. If the user you installed SQL Express is the same as you are developing with now, you are fine leaving the options as on the screenshot.


Figure 4: By right-clicking on Tables, you can select “Add Table” to create a new table. Do that, and create a table in designer mode just as shown on the screenshot. Insert some data, too:


Fast, isn’t it? At this point, you should not have wasted more than 15-20 Minutes, even if you are new to this way of creating a DB. Now we are going to set up a project that can actually transfer our Book entity from the DB to a .NET class.

1.2 Setting up NHinbernate

Our first step is to create a new application. For now, a simple Console application will do. Let’s call it DevJour1.

Next, we need to add the necessary DLLs in order to get nhibernate running

Create a subfolder lib in your project’s directory (e.g. C:\DevJour1\lib)

Copy all DLLs from the Required_Bins directory (of the extracted nhibernate zip file) into the \lib subfolder

Copy all DLLs from Required_For_LazyLoading\Castle directory (of the extracted nhibernate zip file into \lib

In VS, right-click on the project, ->References and go to Add reference. Add the DLLs from our newly created subfolder as shown on the screenshot:

Adding references to the projectLet’s This was it already! We’re set up and ready for the mapping! Let’s move on to Part 2!

Best regards,


Read Full Post »

Hello, folks!

It’s deep in the winter, so it’s time for what? Exactly: Hibernation! The (n)hibernate framework offers you persistence of existing (.NET) objects to/from a DB (various DBMS supported, among them Oracle, MSSQL, DB2, SQLLite etc.). This way you can realize all the CRUD operations using .NET objects while the framework will generate the necessary underlying SQL statements. On top of that, it can also perform sorting, range-based retrieval and much more for you. And in the end, you will end up with a transparent mapping of one or more DBs into your own (reusable) framework.

Why is that cool?

  • Easier maintenance (DB changes will be reflected in the nhibernate mappings, hence in the underlying objects, not on higher levels)
  • Mapping multiple DBs into one codebase
  • Avoidance of DB-dependent constructs, such as packages, procedures
  • Possibility to improve speed through caching the objects

The following (announced) article series will get you started with your first  nhibernate mapping steps. It is intended for an audience, who is already somewhat confident in using databases and C# (or at least, any .NET programming language). However, some experience in C#, XML and concepts of DBs is required. Here comes a list with the topics covered in the article series:

More points to be announced!

Best regards,

Read Full Post »