First you need to add a set of properties to your tables:
- Version - time of last modification (can also be autoincrementing counter instead of time).
- LastModifiedBy - reference to the user which made last modification (if you store that).
Then you have several options about how to store your version history. You can
Create a new table for each of the main tables you want to store history for. That history tables will have all the same fields as main table, but primary and foreign keys will not be enforced. For each foreign key also store Version of referenced entry at the time version was created.
OR you can serialize everything interesting about your entity and store all that serialized blobs for all entities you want to version in one global history table (I personally prefer first approach).
How do you fill your history tables? Via update and delete triggers.
- In update trigger for your entity - copy all previous values to the history table. For each foreign key - also copy current Version of referenced entity.
- In delete trigger - basically do the same.
Note that more and more modern systems do NOT really delete anything. They just mark things as deleted. If you would want to follow this pattern (which has several benefits) - instead of deleting add IsDeleted flag to your entities (of course you then have to filter deleted entities out everywhere).
How do you view your history? Just use history table, since it has all the same properties as main table - should not be a problem. But - when expanding foreign keys - ensure that referenced entity Version is the same as you store in your history table. If it's not - you need to go to History table of that referenced entity and grab values there. This way you will always have a snapshot of how entity looked like at THAT moment, including all references.
In addition to all above - you can also restore state of your entity to any previous version.
Note that this implementation, while easy, can consume some space, because it stores snapshot, not only changes being made. If you want to just store changes - in update trigger you can detect what fields has been changed, serialize them and store in global history table. That way you can at least show in user interface what has been changed and by whom (though you might have troubles to reverting to some previous version).
EF
) could be used as a base for enterprise application (concerning delete action and m-m relationships) – Basicity