In web.config, define Entity Framework SetInitializer.

entity-framework web-config


Right now, in development I have the following code in the Global.asax.cs file that calls the Entity Framework (v4.1) SetInitializer with my SeedSampleData method. This all works perfectly.

However, I would like to store the SetInitializer "strategy" parameter through a web.config setting so that I can create a deployement script that will automatically set it to new System.Data.Entity.CreateDatabaseIfNotExists<EfDbContext>() instead of my seed method during production deployment.

The reason for wanting to move this to the web.config is that when I roll out a new deployment to the production server I want to make sure that I don't accidentally leave my seed initializer in the code.

protected void Application_Start()
  //TODO: Figure out how to move the following lines to web.config and have a deployment script modify it when going to production.

  //This line is for production
  //System.Data.Entity.Database.SetInitializer(new System.Data.Entity.CreateDatabaseIfNotExists<EfDbContext>());

  //This line is for development
  System.Data.Entity.Database.SetInitializer(new Domain.Concrete.SeedSampleData());

  //... Remainder of Application_Start calls here...
3/12/2012 8:53:31 PM

Accepted Answer

If you update to EF 4.3 (which is a good idea anyway), then you can use something like this in your web config:

    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089" />

      <context type=" Blogging.BlogContext, MyAssembly">
        <databaseInitializer type="Blogging.MyCustomBlogInitializer, MyAssembly" />

Rowan wrote about it in detail here:

If you really want to keep using 4.1, then there is an older syntax that you can use instead. I wrote about it here:

3/13/2012 5:10:38 AM

Popular Answer

If I understand correctly, your SeedSampleData initializer is used only for debug purposes?

I don't know if there is a config parameter to control this, but you can use preprocessor directives:

System.Data.Entity.Database.SetInitializer(new Domain.Concrete.SeedSampleData());
System.Data.Entity.Database.SetInitializer(new System.Data.Entity.CreateDatabaseIfNotExists<EfDbContext>();

(assuming, of course, that you don't deploy debug assemblies in production...)

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow