title: entity framework create history tables for entities
body: <p>We would like to create a history table for each of our entities.
  Is there a way to have entity framework create the history entities/tables automatically, given the existing entities?</p>
  
  <p>For example, the <code>Customer</code> entity would have a shadow history table called <code>CustomerHistory</code>.  Whenever there is an edit or a delete, the old record will be inserted into the history table.   The main entity table will always contain the current record.</p>
  
  <p>Since we have several entities, I would rather not have to create a separate history entity and repository for each entity, thus doubling the entities.</p>
  
  <p>We would like to do this for all of our entities in order to track transactional and state temporal changes to the entities.</p>
  
  <p>We use the unit of work and repository patterns.</p>
  
  <p>Assume that the properties of the Entity and the <code>EntityHistory</code> objects would be the same, although we may want to extend the history object with some datetime properties.</p>
  
  <p>I understand how to <a href="http://jmdority.wordpress.com/2011/07/20/using-entity-framework-4-1-dbcontext-change-tracking-for-audit-logging/" rel="noreferrer">override <code>DbContext.SaveChanges</code> in order to write to history/audit tables</a>.</p>
  
  <p>What I want to avoid doing is having to create duplicate history entities/repositories for every entity that we have.</p>
  
  <p>I am currently exploring doing something in <code>OnModelCreating</code> to create a history entity for each entity  but have not found a good example.</p>
  
  <p>Any ideas?</p>