views:

17

answers:

1

I have a situation where I have a table that has a soft foreign key to link records in the table to one of many other tables depending on another value in the table. To demonstrate:

TableOfTables: Id, TableName

HistoryTable: Id, TableOfTableId, NumberedTableId, etc...

Table1: Id, etc...

Table2: Id, etc...

Table3: Id, etc...

TableOfTables contains a record for each numbered table in the database (Table1, Table2, Table3, ...). The HistoryTable has a foreign key to this table (TableOfTableId). It also has a column, NumberedTableId which is a reference to the Id column of the numbered tables.

Now, this works just fine, but there is no referential integrity between NumberedTableId and the Id columns of the numbered tables. Now as far as I am aware you cannot create a sort of conditional foreign key that can point at different tables depending on some condition...so what would be the best way to get referential integrity here?

The only two things I can think of are to have lots of nullable NumberedTableId columns in the HistoryTable, each one with a foreign key to a specific numbered table with the rest of the columns filled with nulls...ugly, or to have a seperate HistoryTable for each numbered table...this will mean lots of HistoryTables as there are many numbered tables in our database.

What is my best option here? History table is really a logging table that records changes and who changed values in the numbered tables, its not used for anything other than auditing and not read at all by our program, but I don't like not having total referential integrity.

What are my options here? Any solution needs to be able to work with Entity Framework 4.0.

Thanks

+1  A: 

Actually, there are three options (you have mentioned two but I'll restate them here)

  1. Multiple FK columns with a check constraint to enforce that a given row can only have a single FK value.
  2. Multiple history tables
  3. A single history table with a triggers from hell to enforce referential integrity (triggers on the source tables and the history table).

There is no clean answer. My approach to this problem has been to have a history table for each table of current data with a foreign key and cascade update and delete. This at least avoids a bottleneck on a single table, allows for referential integrity and is clear to other developers.

Thomas