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

后端 未结 5 631
有刺的猬
有刺的猬 2021-01-01 07:06

I am attempting to deploy my first alpha version of a system online for a few people to start using. On development I make heavy use of the DropCreateDatabaseOnModelC

相关标签:
5条回答
  • 2021-01-01 07:14

    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");
        }
    }
    
    0 讨论(0)
  • 2021-01-01 07:18

    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());
        }
      }
    }
    
    0 讨论(0)
  • 2021-01-01 07:20

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

    0 讨论(0)
  • 2021-01-01 07:21

    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.

    0 讨论(0)
  • 2021-01-01 07:32

    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();
    }
    
    0 讨论(0)
提交回复
热议问题