27 November 2014

Relations in Object-Relational Mapping

Don’t let your ORM take care of relationships.

Let’s face it: Even though you know him to potentially cause lots of harm, you still rely on your favorite ORM. There are lots of very valid points to criticize about these peculiar things. But given proper usage, their benefits arguably justify their existence.

To save yourself a fair bit of trouble you should follow a number of best practices anyhow, one of which I am going to lay before you in this short post.

Never make “use” of an ORM’s “capability” to manage relations between objects for you.

The reason for this is simple: Meta-data is everywhere but never accounted for. At some point in the development of any sufficiently complex data-model, you will want to tie some bits of information to a relationship. A to-do-item in multiple lists might need to be assigned a priority in each of these, an “assigned-to” relation probably wants to store the date of the assignment. Tying this kind of information directly to the relation is not only elegant (think graphs with labeled edges) but also tremendously practical. Continuing with the above example: Unassigning a task from someone by deleting the relation will keep the database consistent. If I had stored the same information in a separate model extra care would need to be taken in order to clean everything up correctly.

As I am writing this, I am already looking forward to the third manual schema update this year alone, because what used to be a simple relation suddenly required a tiny field of meta-data.