Csharp Code Samples

Rohan’s Blog – C# .NET Programming
  • rss
  • Home
  • About
  • Search
  • Contact Me

Nhibernate Parent Child Relations

Rohan Warang | August 1, 2009

For almost every Nhibernate beginner the most challenging thing to do is implement a parent child or one to many relation. There are many articles about this on the net some very basic and some highly detailed. But most samples available do not run when you download them giving all sorts of Nhibernate errors, which well obviously make no sense to someone who is using Nhibernate for the first time.

So this is my attempt at building a small Nhibernate one to many sample that will hopefully run without any issues and help in implementing basic relations using Nhibernate.

The Database Structure

The database structure I have chosen is a one to many relation between Department and User, where one department can have multiple users. The entity relation diagram is as shown below.

NHSample_dbStructure

Building the ORM

We will be building a new class library which may be considered as a data layer using Nhibernate. The object relation mapping for Nhibernate needs to be defined as shown below.

NHSample_ClassDiagram

The class structure is exactly similar to the database entity diagram shown above. Each property in the class maps to a column in the database. However you may notice that there is no Department Id column in User class. Instead the foreign key relation is established by the user list defined in Department class. This collection is similar to a foreign key relation in the database.

The next step is to define the Database to Class mapping in XML files. For the user class create a new XML file and name it User.hbm.xml. The .hbm is required for Nhibernate to compile it.

Show Code

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
        namespace="NHibernateSample" assembly="NHibernateSample">
	<class name="User" table="USER_DATA">
		<id name="UserId" column="USER_ID">
			<generator class="native" />
		</id>
		<property name="UserName">
			<column name="USER_NAME" not-null="true" />
		</property>
		<property name="Email">
			<column name="EMAIL" not-null="true" />
		</property>
	</class>
</hibernate-mapping>

Similarly for the department class define an Department.hbm.xml file as shown below.

Show Code

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
        namespace="NHibernateSample" assembly="NHibernateSample">
	<class name="Department" table="DEPARTMENT">
		<id name="DepartmentId" column="DEPARTMENT_ID">
			<generator class="native" />
		</id>
		<property name="DepartmentName">
			<column name="DEPARTMENT_NAME" not-null="true" />
		</property>
		<bag name="UserList" cascade="all" lazy="false">
			<key column="DEPARTMENT_ID"/>
			<one-to-many class="User"/>
		</bag>
	</class>
</hibernate-mapping>

For the collection we use a tag called bag which defines relation between the two classes.

Now one at a time right click the hbm files and in their properties set the Build Action as Embedded Resource. This will embed the xml files in the dll.

Building A Session Factory

For Nhibernate to connect to a database we need to declare a Session Factory which will build an Nhibernate session.

Show Code

class SessionFactory
{
    private static Configuration config;

    static SessionFactory()
    {
        if (config == null)
        {
            config = new Configuration();
            config.Configure();
            config.AddAssembly("NHibernateSample");
        }
    }

    public static ISession Session
    {
        get { return config.BuildSessionFactory().OpenSession(); }
    }
}

Performing Operations

Create a new session object for performing operations on database. For example to create a new department declare a department object and save it using ISession.Save(object).

Show Code

public static void Add(Department department)
{
    using (ISession session = SessionFactory.Session)
    {
        using (ITransaction transaction = session.BeginTransaction())
        {
            session.Save(department);
            transaction.Commit();
        }
    }
}

Refer the attached sample for more operations.

Running the Sample

The sample contains a SQL 2008 database mdf file which contains the table structure required to test the sample. Open the App.config file in TestProject and modify the connection string and give the exact location of that file on your file system. Also provide the user name password for your local sql server instance.

Show Code

<property name="connection.connection_string">
  Server=.\SQLExpress;
  AttachDbFilename=C:\NHibernateSample\TestDatabase\TestDatabase.mdf;
  user=username;password=password;
</property>

If you have an instance of SQL server 2005 installed, modify the dialect tag as shown below.

Show Code

<property name="dialect">
  NHibernate.Dialect.MsSql2005Dialect
</property>

Download Sample
NHibernateSample.zip

Categories
Tutorials
Tags
Nhibernate, Parent Child
Comments rss
Comments rss
Trackback
Trackback

« Update Panels and JSON Alternatives

3 Responses to “Nhibernate Parent Child Relations”

  1. feel says:
    January 16, 2010 at 7:14 pm

    thanks for information for c# artical i am looking for download

    http://csharptalk.com

    feel

  2. Ted says:
    January 19, 2010 at 10:49 pm

    In no way did I manage to open or attach the database file. Attempts with both instances SQL 2005 and 2008 failed. I tried everything on earth…

    FCB::Open failed: Could not open file D:\Samples\NHibernateSample\TestDatabase\TestDatabase.mdf for file number 0. OS error: 5(error not found).

    I also gave all security rights on the SQL service user with no success.

  3. Ted says:
    January 20, 2010 at 6:01 pm

    I fixed the problem for me.
    The database is detached from SQL 2008. Though there is COMPATIBILITY_LEVEL = 90 set in, it still “cannot be opened because it is version 655. This server supports version 612 and earlier”.
    I attached it in SQL2008, scripted in sql text file, removed the 2008-specific lines:

    ALTER DATABASE [TestDatabase] SET COMPATIBILITY_LEVEL = 90
    ALTER DATABASE [TestDatabase] SET HONOR_BROKER_PRIORITY OFF

    And ran the create script in SQL 2005. Then I changed the “connection.connection_string” property in app.config to:
    “Server=.\SQLExpress;Database=TestDatabase;…..”
    and it’s finally OK in SQL2005.
    Still cannot figure out why it wouldn’t just open the mdb neither in 2005 nor in 2008…

Leave a Reply

Click here to cancel reply.

Spam protection by WP Captcha-Free

Subscribe

dZone

Categories

  • Optimization
  • Tutorials

Admin

  • Log in
Creative Commons License rss Comments rss valid xhtml 1.1 design by jide powered by Wordpress get firefox