I’m faced with a decision, I need to make tables for Items for my campaign manager. I wanted to start with a generic “Item” item, and inherit from it depending on the type of item it was. Looking into how Entity Framework wanted to handle it, I had basically two design options for doing this, Table Per Hierarchy or Table Per Type:
- Table Per Hierarchy (TPH): Creating one table that contains all the data for the item and filters based on what info I need
- Table Per Type (TPT): A seperate table for each type.
A part of me loves the idea of the second option, because it seems to me to following “correct” programming paradigms. However as I read into it, I learned doing a TPT style could impact performance negatively. If I have to trade a bit of maintainability on my end for performance on the application, I think it’s worth it in this case. Nobody likes slow software. I decided to opt for the standard TPH, risking sparse Item table. Maybe it will bite me in the ass down the line ,we’ll see.
Getting it set up was simple thanks to EF. I made two subclasses as a proof of concept:
Then I had to add all of these to the DbContext:
Unlike everything else I’ve added to the DB so far, weapon and potion are not being linked up to the table. I’m making the model builder aware of them so it knows how to build them in the database, but because they both inherit from Item, the single DbSet<Item> Items will handle creating a TPH style table.
And there we have it. I still have to go through the process of creating and adding items of each type, and this table is going to grow as I think of more Item types. I do think about just how many columns I’ll end up and just how sparse it will be. It’s hard to say just yet, hopefully I can keep it small.