Sunday, July 17, 2011

Understanding One to Many relationships in NHibernate

One to many relationships in a relational model is probably the most common kind of relationship used in a relational database. Typically, the table in the “many” side of the relationship contains a special column in which each row contains the Id of the corresponding row in the table at the ‘one’ side.

Even though this is very straight-forward in the relational database model, there are many nuances as how to map it to the object-oriented model. These nuances confuses many developers, especially those new to NHibernate. In this post I’ll try to explain each of these nuances one by one, so the next time you’ll need to map a one-to-many relationship you’ll understand what you’re doing.

If you don’t care to not understand what you’re doing, but only want a quick reference on what to use when, you can just directly to the end of this post.
Which side contains a reference to the other side?

First, let’s distinguish between 3 major kinds on one-to-many relationships, as they are modeled in code:

  • The ‘many’ side points to the ‘one’ side (similar to the relational model). Note that the Customer doesn’t hold a collection of its Orders. I like to refer to these kind of relationships as “foreign key relationships”

image_thumb_1E6D21E0.png

  • The ‘one’ side contains a property which is a collection (e.g. IList) that references all of the elements in the ‘many’ side. I like to refer to this kind of relationships as “parent/child relationships” (the ‘one’ has many children)
image_thumb_6FC6F330.png


Read more: ArnonA
QR: understanding-one-to-many-relationships-in-nhibernate.aspx

Posted via email from Jasper-Net