Reputation: 63
I have a DBConfiguration with a constructor having only one line:
SetDatabaseInitializer(new MigrateDatabaseToLatestVersion<SchedulingReadContext, Configuration>());
For testing I am trying to use a different initializer by doing the following in SetUp
Database.SetInitializer(new DropCreateAndMigrateDatabaseInitializer<SchedulingReadContext, Configuration>());
using (var context = new SchedulingReadContext())
{
context.Database.Initialize(true);
}
However while debugging if I step into Database.SetInitializer, I end up in the DBContext constructor, so my DatabaseInitializer does not change.
Any solution would be helpful, Thanks
Upvotes: 1
Views: 367
Reputation: 1748
You need to set the Database Initializer conditionally so you're only calling Database.SetInitializer
once.
I usually use an appSetting in my web.config which denotes what environment the application is running in as follows:
<add key="EnvironmentIn" value="development"/> // change this to whatever environment you are working in
Then in the constructor of your DbConfiguration check this setting and set the initializer accordingly:
if (ConfigurationManager.AppSettings["EnvironmentIn"] == "development")
{
SetDatabaseInitializer(new DropCreateAndMigrateDatabaseInitializer<SchedulingReadContext>());
}
else
{
SetDatabaseInitializer(new MigrateDatabaseToLatestVersion<SchedulingReadContext, Configuration>());
}
Upvotes: 2