I'm trying to figure out the best way to map inheritance relationships in an object model into a relational database. For example consider the following class structure.
public Class Item
{
public String Name{get; set;}
public int Size {get; set}
}
public Class Widget:Item
{
public String Color{get; set;}
}
public Class Doohicky:Item
{
public String Smell{get; set;}
}
Here's are a few options I'm considering for how to save this structure to a database.
Options 1: Single Table for all item types
Items Table: ItemID, Name, Color, Smell
This sucks as it would require NULL values.
Options 2: Separate tables for each item type
Widgets Table: WidgetID, Name, Color
Doohicky Table: DoohickyID, Name, Smell
This is better, but would be more difficult to list all Items
Options 3: Linked tables
Items Table: ItemID (PK), Name, Size
Widgets Table: WidgetID (PK), ItemID (FK), Color
Doohicky Table: DoohickyID (PK), ItemID (FK), Smell
I think this option is the best, as it prevents me from having Null values in any fields, plus it will make it easier to list all the Items, and/or create a list of a specific type of Item (Widgets or Doohickies).
However, I'm not sure how to create the relationship between the Items table and the Widgets and Doohickies tables. I don't want to end up with row in either table referencing the same ItemID in the Items table.
For example when I add an entry to the Widgets table, how can I ensure that it is linked to a new entry in the Items table with a unique ItemID? Should I instead only track the ItemID rather then separate type specific IDs like WidgetID and DoohickyID, and use it to create a one to one relationships between the Items table and the type specific tables?
Options 4
Items Table: ItemID (PK), Name, Size
Widgets Table: ItemID (PK), Color
Doohicky Table: ItemID (PK), Smell