Forward Compatibility in Code First Data Module
By default, Code First will create a database automatically if the database it targets doesn’t exist. For some folks, this will be the desired functionality even when deploying, and just the production database will be created the first time the application launches. If you have a DBA taking care of your production environment, it’s far more likely that the DBA will create the production database for you, and once your application is deployed it should fail if the database it targets doesn’t exist. In this article, I’ve also overridden the default initializer logic and have configured the database to be dropped and recreated whenever my schema changes. This is definitely not something you want to leave in place once you deploy to production.
The recommended approach for changing or disabling initializer behavior when deploying is to use the App.config file (or Web.config for Web applications). In the appSettings section, add an entry whose key is DatabaseInitializerForType, followed by the context type name and the assembly in which it’s defined. The value can either be “Disabled” or the initializer type name followed by the assembly in which it’s defined.
The following example disables any initializer logic for the context I’ve been using in this article:
<appSettings>
<add
key="DatabaseInitializerForType Blogging.BlogContext, Blogging"
value="Disabled" />
</appSettings>
The following example will change the initializer back to the default functionality that will create the database only if it doesn’t exist:
<appSettings>
<add
key="DatabaseInitializerForType Blogging.BlogContext, Blogging"
value="System.Data.Entity.CreateDatabaseIfNotExists EntityFramework" />
</appSettings>
namespace Blogging
{
public class BlogContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// TODO: Perform any fluent API configuration here!
}
}
}
or
set your database initialization strategy to null to prevent your context from checking to see if there are any discrepancies
Database.SetInitializer<YourContext>(null);
Enjoy!!