Techniques - DevSource
DevSource: Microsoft Developer Resource DevSource Home Sponsored by Microsoft Home Add Ons Architecture Languages Techniques Using VS Forums
Home arrow Techniques arrow Page 3 - Getting Started with NHibernate
Getting Started with NHibernate
By Shawn Wildermuth

Rate This Article: Add This Article To:

Getting Started with NHibernate - ' NHibernate Relationships '
( Page 3 of 4 )

Relationships

Since NHibernate is attempting to map a database to your business objects, handing the relationship between objects is central to making this helpful at all.

ADVERTISEMENT

Luckily, NHibernate does support this idea of relationships between objects.

To get started, let's first add a new Order class to hold orders for our customers.

This simple class will hold our orders with a couple pieces of interesting information: order number, customer number, order date, and ship date.

using System;
using System.Collections.Generic;
using System.Text;

namespace RelationshipExample
{
  public class Order
  {
    int _orderID;

    public int OrderID
    {
      get { return _orderID; }
      set { _orderID = value; }
    }

    string _customerID;

    public string CustomerID
    {
      get { return _customerID; }
      set { _customerID = value; }
    }

    DateTime _orderDate;

    public DateTime OrderDate
    {
      get { return _orderDate; }
      set { _orderDate = value; }
    }

    DateTime _shippedDate;

    public DateTime ShippedDate
    {
      get { return _shippedDate; }
      set { _shippedDate = value; }
    }

  }
}

As with the customer class, we can define a new mapping file to map this to the database:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.0">
  <class name="RelationshipExample.Order, RelationshipExample" 
         table="Orders">
    <id name="OrderID" type="Int32">
      <generator class="assigned" />
    </id>
    <property name="CustomerID" 
              type="String"/>
    <property name="OrderDate" 
              type="DateTime"/>
    <property name="ShippedDate" 
              type="DateTime"/>
  </class>
</hibernate-mapping>

Now that we have an order object that can be serialized, we need to relate it to the customer class. First, we must add a new Orders property on the Customer class:

public class Customer
{
  // ...

  IList _orders;

  public IList Orders
  {
    get { return _orders; }
    set { _orders = value; }
  } 
}

Next, we change our Customer mapping file to include the relationship:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.0">
  <class name="RelationshipExample.Customer, RelationshipExample" 
         table="Customers">
    <id name="CustomerID" type="String" length="5">
      <generator class="assigned" />
    </id>
    <property name="CompanyName" 
              type="String" length="40"/>
    <property name="ContactName" 
              type="String" length="30"/>
    <property name="ContactTitle" 
              type="String" length="30"/>
    <property name="Phone" 
              type="String" length="24"/>
    <bag name="Orders">
      <key column="CustomerID" />
      <one-to-many 
        class="RelationshipExample.Order, RelationshipExample" />
    </bag>
  </class>
</hibernate-mapping>

To add the relationship, we added a bag element that specifies the name of the new property on the Customer class. Inside the bag element are two sub-elements: key and 'one-to-many'. The key element specifies the name of the property inside the related entity, which it uses as the link between the two elements. The 'one-to-many' element specifies the .NET type to map to the new collection.

Once we set up this relationship, we can use NHibernate to load our object and its related entities, like so:

// Loads the NHibernate Types to 
// prepare for Serialization
Configuration cfg = new Configuration();
cfg.AddAssembly("RelationshipExample");

// Opens a session to NHiberbate to allow
// us to work with objects
ISessionFactory factory = cfg.BuildSessionFactory();
using (ISession session = factory.OpenSession())
{
  // Loads a specific object from the database
  Customer customer = (Customer)
    session.Load(typeof(Customer), "ALFKI");

  // Show Customer
  theList.Items.Add("Customer: " + customer.CompanyName);

  // Show each Order
  foreach (Order order in customer.Orders)
  {
    theList.Items.Add("  Order: " + order.OrderID);
  }

  session.Close();
}

We can load our customer in the same way we did in the first example. However, now we can also show the orders that are related to our customer by enumerating the orders within the customer object.



 
 
>>> More Techniques Articles          >>> More By Shawn Wildermuth
 



Microsoft's Future: A Chat With Their CTO, Barry Briggs

Play Video >

All Videos >

Julia explores the Robotics Studio!

Read now >

Messages to Bill Gates!

Read now >

View Now
DevSource RSS FEEDS
XML Want an easy way to keep up with breaking tech news? And the Get DevSource headlines delivered to your desktop with RSS.