Brosteins

Developers, Technology Evangelists, Bros.

NHibernate Map by Code Examples – Part 1

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”
    • IdBag
    • Formula
    • EnumStringType<>

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!

3 comments for “NHibernate Map by Code Examples – Part 1

  1. September 4, 2014 at 9:42 pm

    Nick, which version of NHibernate are you blogging about? there aren’t any virtual properties in your classes definition, perhaps, I missed out changes in NH core.

    • Nick Branstein
      September 5, 2014 at 12:16 pm

      Sokun thanks I neglected to list the NHibernate version here (3.3.3). 4.0 has recently come out and I have not tested everything yet but I do believe most of the Map By Code functionality remains the same. I have also updated my Gists to add the virtual properties as required by NHibernate – good catch!

Leave a Reply

Your email address will not be published. Required fields are marked *