title: Entity Framework CTP 4 - Code First Custom Database Initializer
body: <p>I would like to implement a custom database initialization strategy so that I can generate the database schema and apply it to an EXISTING EMPTY SQL database using a supplied User ID and Password. </p>
  
  <p>Unfortunately the built-in strategies don’t provide what I’m looking for:</p>
  
  <pre><code>// The default strategy creates the DB only if it doesn't exist - but it does 
  // exist so this does nothing
  Database.SetInitializer(new CreateDatabaseOnlyIfNotExists&lt;DataContext&gt;());
  
  // Drops and re-creates the database but then this breaks my security mapping and 
  // only works if using a “Trusted" connection
  Database.SetInitializer(new RecreateDatabaseIfModelChanges&lt;DataContext&gt;());
  
  // Strategy for always recreating the DB every time the app is run. – no good for 
  // what I want
  Database.SetInitializer(new AlwaysRecreateDatabase&lt;DataContext&gt;());
  </code></pre>
  
  <p>I have worked out the following but this does not create the ModelHash so I’m unable to use <strong>"context.Database.ModelMatchesDatabase()"</strong> to validate that the database schema has been created and prevent multiple initializations:</p>
  
  <pre><code>public class Initializer : IDatabaseInitializer&lt;DataContext&gt;  
  { 
      Public void InitializeDatabase(DataContext context)  
      {       
           // this generates the SQL script from my POCO Classes
           var sql = context.ObjectContext.CreateDatabaseScript();
  
           // As expected - when run the second time it bombs out here with "there is already an
           // object named xxxxx in the database"
           context.ObjectContext.ExecuteStoreCommand(sql); 
  
           this.seed(context)
           context.SaveChanges();
      }
  }  
  </code></pre>
  
  <p>Questions:</p>
  
  <p>Does anyone know how I can get/create the model hash? (which is an EdmMetadata Entity)</p>
  
  <p>-Or-</p>
  
  <p>Is there a better way of doing this in general using the Code First CTP?</p>