How do I allow the EF4 CodeFirst database initializer to run under development, but not run in production

人走茶凉 提交于 2019-11-30 10:23:01

You can always create a new Configuration (in addition to Debug and Release). You would then define a Conditional Compilation Symbol for the new configuration. For example if I created a new configuration called LocalDebug (with the same settings at the default debug) I would then add LOCALDEBUG to the Conditional Compilation Symbols. With this defined you can use:

#if LOCALDEBUG
  //do database stuff
#endif

Then you can still deploy the built in debug configuration and this section will not fire.

What about inversion of control:

var initializer = container.Resolve<IDatabaseInitializer<Context>>();
Database.SetInitializer(initializer);

Based on your IoC configuration you will either return developement or production initializer. You can have different configuration file for each build configuration so you can also have IoC container configured differently.

public class ThrowExceptionInitializer : IDatabaseInitializer<Context>
{
    public InitializeDatabase(Context context)
    {
        // Custom exception
        throw new InvalidVersionException("The new application version is not supported by the database version");
    }
}

As @Johann says, the ConditionalAttribute is probably the cleanes solution here:

[Conditional("DEBUG")]
private void InitializeDb()
{
    // Initializer code here
    // DropCreateDatabaseOnModelChange<TContext>
}

and in Global.asax:

public void Application_Start // or wherever it is you're initializing
{
    // This will only be called if the DEBUG constant is defined
    InitializeDb();
}

You could use the Conditional attribute but it is not so different from the #ifdef

If you are using sql express in development and not on your production box you can filter by the connection.

protected void Application_Start(object sender, EventArgs e)
{
  using (var db = new MyDb())
  {
    if (db.Database.Connection.DataSource.IndexOf("sqlexpress", StringComparison.InvariantCultureIgnoreCase) > -1)
    {
        Database.SetInitializer(new MyDbInitializer());
    }
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!