在web.config中定义实体框架SetInitializer

big*_*mac 16 entity-framework web-config

现在,在开发中,我在Global.asax.cs文件中有以下代码,使用我的SeedSampleData方法调用Entity Framework(v4.1)SetInitializer.一切都很完美.

但是,我想通过web.config设置存储SetInitializer"strategy"参数,以便我可以创建一个deployement脚本,new System.Data.Entity.CreateDatabaseIfNotExists<EfDbContext>()在生产部署期间自动将其设置为而不是我的种子方法.

想要将其移动到web.config的原因是当我将新部署推广到生产服务器时,我想确保我不会意外地将我的种子初始化程序留在代码中.

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...
}
Run Code Online (Sandbox Code Playgroud)

Art*_*ers 19

如果你更新到EF 4.3(无论如何这是一个好主意),那么你可以在你的web配置中使用这样的东西:

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

  <entityFramework>
    <contexts>
      <context type=" Blogging.BlogContext, MyAssembly">
        <databaseInitializer type="Blogging.MyCustomBlogInitializer, MyAssembly" />
      </context>
    </contexts>
  </entityFramework>
</configuration>
Run Code Online (Sandbox Code Playgroud)

Rowan在这里详细介绍了它:http://blogs.msdn.com/b/adonet/archive/2012/01/12/ef-4-3-configuration-file-settings.aspx

如果您真的想继续使用4.1,那么可以使用较旧的语法.我在这里写到:http://blog.oneunicorn.com/2011/03/31/configuring-database-initializers-in-a-config-file/