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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…