Professional Documents
Culture Documents
NHibernate can be used to treat database relational tables as if they are objects. What this
means is we can have a class representing an object with its properties. The class objected can
be used to save and retrieve data from the database without manually writing the SQL
statements.
Crea
te a new project and name it CustomerRecords Rename Form1.cs to frmCustomers Design the
above graphical user interface and set the properties for the controls as follows
S/N CONTROL PROPERTY VALUE
1 FORM Name frmCustomers
2 FORM Text Customer Records
3 DataGridView Name dgvCustomers
4 Label Text Customer ID
5 TextBox Name txtCustomerID
6 Button Name txtClear
7 Button Text Clear
8 Button Name txtAddNew
9 Button Text Add New
10 Button Name txtUpdate
11 Button Text Update
12 Button Name txtDelete
13 Button Text Delete
14 Label Text Customer Name
15 TextBox Name txtName
16 Label Text Email
17 TextBox Name txtEmail
18 Label Text Contact Person
19 TextBox Name txtContactPerson
20 Label Text Contact Number
21 TextBox Name txtContactNumber
22 Label Text Physical Address
23 TextBox Name txtPhysicalAddress
24 Label Text Postal Address
25 TextBox Name txtPostalAddress
Add a new class and name it Customers.cs Add a new XML file and name it
Customers.hbm.xml Your project structure should now look as
follows
NHibernate References
Download NHibernate from this link. Unzip the contents of the download. Right click on
references from the solution explorer Browse to the folder where you unzipped the files you
downloaded Browse to the Required_Bins directory. It has two dll files lesi.Collections.dll and
NHibernate.dll Add both files as shown in the image
below
Cl
ick on OK button when done
NHibernate Class
The Customers class will represent the customer object. We will now create properties in the
customer class that will match the fields in the database. Add the following code to Customers.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CustomerRecords
{
class Customers
{
public virtual int customer_id { get; set; }
public virtual string name { get; set; }
public virtual string email { get; set; }
public virtual string contact_person { get; set; }
public virtual string postal_address { get; set; }
public virtual string physical_address { get; set; }
public virtual string contact_number { get; set; }
}
}
HERE,
“public virtual int property { get; set; }” sets a class property that matches a field in
the database. Note the property is defined with a virtual keyword. This makes it possible
for the fields to be overridden.
NHibernate Mapping
NHibernate uses XML files for mapping database fields to objects properties. The XML file
should always end with *.hbm.xml extension. Open the file Customers.hbm.xml Add the following
code
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
assembly="CustomerRecords" namespace="CustomerRecords">
<class name="Customers">
<id name="customer_id">
<generator class="native" />
</id>
<property name="name" />
<property name="email" />
<property name="contact_person" />
<property name="postal_address" />
<property name="physical_address" />
<property name="contact_number" />
</class>
</hibernate-mapping>
HERE,
“<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
assembly="CustomerRecords" namespace="CustomerRecords">…</ hibernate-
mapping>” is the root element of the mapping file. The element has xmlns, assembly
and namespace attributes. The assembly and namespace attributes should match your
project assembly and namespace values.
“<class name="Customers">…</class>” defines the class element.
“<id name="customer_id">…</id>” defines primary key. In our case its customer_id
“<property name="field_name" />” matches the fields in the table that you wish to
manipulate using NHibernate.
For NHibernate to recognize our *.hbm.xml file, we need to set it as an embedded
resource.
Click on Customers.hbm.xml file in Solution Explorer Set the Build Action to Embedded
Resource
NHibernate Connect to SQL Server
In this example, we will use an SQL Server database. Our database will have a single table. Run
the following script to create the database
CREATE DATABASE [CustomerRecordsDB]
GO
USE [CustomerRecordsDB]
GO
SET QUOTED_IDENTIFIER ON
GO
GO
cfg.AddAssembly(Assembly.GetExecutingAssembly());
loadCustomers();
HERE,
“cfg.DataBaseIntegration(x =>….);” sets the database connection string, database
driver and dialect.
“x.ConnectionString “our connection string will connect to the local machine because
we set the server property to a dot. The database used is CustomerRecordsDB and we
are using integrated security.
“x.Driver<SqlClientDriver>();” we will work with SqlClientDriver
“x.Dialect<MsSql2012Dialect>();” we will use the dialect for SQL Server 2012. This will
make available the features in SQL Server 2012.
dgvCustomers.DataSource = customers;
tx.Commit();
}
}
}
HERE,
“var sessionFactory = cfg.BuildSessionFactory();” creates a sessionFactory variable
from our configuration object
“using (var tx = session.BeginTransaction())” creates a transaction from the session
variable”
“var customers = session.CreateCriteria<Customers>().List<Customers>();” retrieves all
the record in Customers table and assigns the results to a list.
“dgvCustomers.DataSource = customers;” assignes the list as the data source to the
data grid.
txtCustomerID.Text =
customer.customer_id.ToString();
txtName.Text = customer.name;
txtEmail.Text = customer.email;
txtContactPerson.Text = customer.contact_person;
txtPhysicalAddress.Text =
customer.physical_address;
txtPostalAddress.Text = customer.postal_address;
txtContactNo.Text = customer.contact_number;
tx.Commit();
}
}
}
Complete NHibernate example source code
This section also adds the code for the command buttons. The code for the buttons is self-
explanatory. If you do not understand or need some clarifications then use the comments section
to ask.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using NHibernate.Cfg;
using NHibernate.Driver;
using NHibernate.Dialect;
using System.Reflection;
using NHibernate;
namespace CustomerRecords
{
public partial class frmCustomers : Form
{
Configuration cfg = new Configuration();
dgvCustomers.DataSource = customers;
tx.Commit();
}
}
}
txtCustomerID.Text =
customer.customer_id.ToString();
txtName.Text = customer.name;
txtEmail.Text = customer.email;
txtContactPerson.Text = customer.contact_person;
txtPhysicalAddress.Text =
customer.physical_address;
txtPostalAddress.Text = customer.postal_address;
txtContactNo.Text = customer.contact_number;
tx.Commit();
}
}
}
public frmCustomers()
{
InitializeComponent();
}
cfg.AddAssembly(Assembly.GetExecutingAssembly());
loadCustomers();
}
customer_id =
int.Parse(dgvCustomers.CurrentRow.Cells[0].Value.ToString());
loadCustomer(customer_id);
}
txtName.Focus();
}
return;
}
customer.customer_id =
int.Parse( txtCustomerID.Text);
customer.name = txtName.Text;
txtEmail.Text = customer.email;
customer.contact_person = txtContactPerson.Text;
customer.physical_address =
txtPhysicalAddress.Text;
customer.postal_address = txtPostalAddress.Text;
customer.contact_number = txtContactNo.Text;
try
{
session.Update(customer);
tx.Commit();
loadCustomers();
}
catch(Exception ex)
{
tx.Rollback();
MessageBox.Show(ex.Message, "Exception
Msg",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
}
}
}
return;
}
customer.name = txtName.Text;
txtEmail.Text = customer.email;
customer.contact_person = txtContactPerson.Text;
customer.physical_address =
txtPhysicalAddress.Text;
customer.postal_address = txtPostalAddress.Text;
customer.contact_number = txtContactNo.Text;
try
{
session.Save(customer);
tx.Commit();
loadCustomers();
}
catch (Exception ex)
{
tx.Rollback();
loadCustomers();
}
}
}
return;
}
try
{
session.Delete(customer);
tx.Commit();
loadCustomers();
}
catch (Exception ex)
{
tx.Rollback();