NHibernate XML Mappings – Part 1 (The Domain Model)
13 June 2010
XML mappings is one of the first things newcomers to NHibernate struggle with. What’s more I’ve found most of the documentation around goes into far more detail than is typically required to get mappings built.
In these posts I’ll go through the basics of mapping out a basic data schema in NHibernate. I don’t intend to cover all the advanced details of mapping, just enough to get you going.
The Schema
Let’s take our classic customers – products – orders environment and map them out using NHibernate.
In our diagram above we’ve got 4 tables with 3 relationships defined:
- 1 Customer to Many OrderMasters
- 1 OrderMaster to Many OrderDetails
- 1 Product to Many OrderDetails
Now lets go map these into C# POCOs. In Visual Studio, add a Class Library to your solution and call it DomainModel.
The Domain
First step is to define some POCOs to hold our data in our domain model. Create four classes as defined below:
Three key points about these POCOs.
- All properties must be virtual for NHibernate’s lazy loading to work.
- When mapping a 1-to-Many, it’s best to use an ICollection
when that collection might be written to in your code. If the collection won’t be changed, rather just use IEnumerable . - I haven’t left any place for the Id columns here, NHibernate can bring them in, but doesn’t need them to be part of your object. When using NHibernate ORM we prefer to pass the actual object around.
That’s it for part 1, our domain model is ready to roll. In part 2 we look at mapping our product class using a simple hbm.xml file.