DaveWentzel.com            All Things Data

Object Relational Mappers Series - Polymorphism Problems

This is the next post on my series on ORMs.  ORM mapping isn't generally complex if the row in the table maps to a simple atomic object in your model.  When there isn't a perfect matching of object to relational model we have some problems.  Polymorphism is an example. 

What Is Polymorphism in the Relational World? 

Simple, we have a number of very similar concepts with only slight differences and we decide to model them in one table with a "type" column to denote the type of concept the row pertains to.  Here's a simple example.  You may decide your database needs the following tables: Employee, Contact, Vendor.  You suddenly realize these three tables share similar cols such as FirstName, LastName, etc.  You decide to build a generic Entity table that contains all of the data you need to support everything and add a "discriminator" flag that can be set to Employee, Contact, or Vendor.  This becomes a wide table with a high degree of data elements that are NULL.  This design violates many relational db design best practices, but it is very common to see models like this. 

How is polymorphism modeled in the ORM tool?  There are a few ways.  The method seen most often is "table per hierarchy."  TPH exacerbates the poor relational design of polymorphism.  This makes us database-centric people hate ORMs even more.  The ORM folks love TPH because they get their reusability and polymorphism. 

The better solution is to use Table per Type (TPT), available with all ORM tools I've used.  In this case every type can have it's own table in the relational model yet we get some of the reusability and polymorphism in the ORM, keeping the developers happy.