Update: Code in this series has been tested with NHibernate’s latest 4.0 as well as 3.3.3.
Recently I wrapped up a large project long term project for a client where NHibernate was used. We chose to use NHIbernate’s Map by Code feature for this project and due to the complex nature of our domain we ran across many different mapping scenarios. While there is some information out there on NHibernate’s map by code, often times we were left to our own vices to figure out exactly how to map our domain entities.
In this series of posts I will show you some tips and tricks we used along the way to map our domain entities.
- Part One
- Many To Many
- Inverse Bag
- Part Two
- JoinedSubClassMapping vs SubclassMapping (Discriminators) vs UnionSubclassMapping
- Part Three
- ForeignKey “none”
Many To Many
For this example let us imagine we have a student and a classroom entity. We may want to access classrooms from the students and vice versa.
Inverse Bag Let’s update our student and give him or her a teacher. Since there are many students per teacher we map this as a simple Many-To-One on the student side. What if we wanted to access all the students that a teacher has but didn’t want to add extra data or create extra tables in the database? Well NHibernate can manage this for you using by mapping a bag on our Teacher and setting Inverse to true. Now every time we have a teacher we have direct access to all the students!
Stay tuned for part two as I go over a few more NHibernate Map By Code examples!