When I create a context with a default connection string (as read from the app.config
) the database is created and the migrations work - basically everything is in order. Whereas when the connection string is created programatically (using SqlConnectionStringBuilder
):
A
);CreateDbIfNotExists()
creates the newest version of database model but the migration mechanisms are not invoked (scenario B
).In A
an exception is thrown when I wish to access the database, as - obviously - it isn't there. In B
database is created properly migration mechanisms are not called, as is the case in standard connection string.
app.config:
"Data Source=localhost\\SQLEXPRESS;Initial Catalog=Db13;User ID=xxx;Password=xxx
"
builder:
sqlBuilder.DataSource = x.DbHost;
sqlBuilder.InitialCatalog = x.DbName;
sqlBuilder.UserID = x.DbUser;
sqlBuilder.Password = x.DbPassword;
initializer:
Database.SetInitializer(
new MigrateDatabaseToLatestVersion<
MyContext,
Migrations.Configuration
>()
);
Specs: Entity Framework: 5.0, DB: SQL Server Express 2008
If your migration does not work correctly try to set Database.Initialize(true)
in DbContext ctor.
public CustomContext(DbConnection connection)
: base(connection, true)
{
Database.Initialize(true);
}
I have similar problem with migrations. And in my solution I have to always set database initializer in ctor, like below
public CustomContext(DbConnection connection)
: base(connection, true)
{
Database.SetInitializer(new CustomInitializer());
Database.Initialize(true);
}
In custom initializer you have to implement InitalizeDatabase(CustomContex context)
method, eg.
class CustomInitializer : IDatabaseInitializer<CustomContext>
{
public void InitializeDatabase(CustomContext context)
{
if (!context.Database.Exists || !context.Database.CompatibleWithModel(false))
{
var configuration = new Configuration();
var migrator = new DbMigrator(configuration);
migrator.Configuration.TargetDatabase = new DbConnectionInfo(context.Database.Connection.ConnectionString, "System.Data.SqlClient");
var migrations = migrator.GetPendingMigrations();
if (migrations.Any())
{
var scriptor = new MigratorScriptingDecorator(migrator);
string script = scriptor.ScriptUpdate(null, migrations.Last());
if (!String.IsNullOrEmpty(script))
{
context.Database.ExecuteSqlCommand(script);
}
}
}
}
}
UPDATED