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

谁说我不能喝 提交于 2019-12-18 13:38:03

问题


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 DropCreateDatabaseOnModelChange<TContext> (I don't have it in front of me at the moment so I can't verify the exact name) to re-initialize my dev database every time my model changes. This happens in the Global.asax.

However, I do not want this to happen on my web host where other people are entering real data. I need to handle all db migrations on there myself so data is preserved.

I had considered #ifdef DEBUG tags to prevent the database initializer from being called, but I don't like that solution. Right now, I have the debug version deployed, so if they come across any errors it is easy for me to see and debug them (this is very very alpha, so only a select few people are using it and know to expect errors).

What other options do I have to prevent Prod DB dropping by EF4 code first?


回答1:


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.




回答2:


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");
    }
}


来源:https://stackoverflow.com/questions/5433318/how-do-i-allow-the-ef4-codefirst-database-initializer-to-run-under-development

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!