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:
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:
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.