Thursday, April 16, 2009

Entity Framework Inheritance

Alex James of the Entity Framework team has been posting tips on Entity Framework practices. You'll find an index to them here; I'm confident he'll maintain it well.

In this post I'm drawing your attention to Tip #12, Choosing an Inheritance Strategy, which is a nifty summary of the issues and tradeoffs for choosing among Table Per Hierarchy (TPH), Table Per Type (TPT) and Table Per Concrete Class (TPC) database representations of class inheritance.

Don't know what those are? Alex is pretty clear on that too.

Which strategy is best?

It depends (hey, ain't that a shock).

Alex walks through the considerations simply and clearly. And, while Alex discusses the choices from an Entity Framework perspective, everything he has to say applies generally. The excellent book "NHibernate in Action" explores this territory well (pages 91-99) and offers similar advice.

Here is the "dirty little secret": inheritance mapping is the most over-hyped feature of sophisticated ORMs.

You rarely need it and you can get into lots of time-wasting trouble.

Yes, I use it from time to time; I like TPH for "code" classes where you're trying to manage thirty or more simple "enumeration-like" classes such as Status, Color, UnitOfMeasure, EmployeeType, etc. All of them have pretty much the same {Id, CodeName, Description} structure.

But I usually avoid inheritance mapping and its attendant complications.

The "NHibernate in Action" authors said it well:

[A]sk yourself whether it might be better to remodel inheritance as delegation in the object model. Complex inheritance is often best avoided for all sorts of reasons unrelated to persistence or ORM. [Your ORM] acts as a buffer between the object and relational models, but that doesn't mean you can completely ignore persistence concerns when designing your object model. [p.98]

I hear echos of that familiar, sound advice: "favor composition over inheritance".

1 comment:

Jules "Gringo Julio" Bartow said...

Now you tell me, "You rarely need it and you can get into lots of time-wasting trouble."

Who'd of thunk ancestors could cause so many problems