移行の Up() メソッドを手動で実行できるようにしたい。現在、私はそれをやろうとしていますが、CreateTable メソッドを含む呼び出しはテーブルを作成しません。接続が正しく設定されていないと思われます。また、それを設定するプロパティはありません。
DbMigrator も試しましたが、いくつかの内部 EF 移行メソッドを呼び出します。
DbMigration.Up メソッドで使用される接続を設定する方法を知っている人はいますか?
前もって感謝します!
移行の Up() メソッドを手動で実行できるようにしたい。現在、私はそれをやろうとしていますが、CreateTable メソッドを含む呼び出しはテーブルを作成しません。接続が正しく設定されていないと思われます。また、それを設定するプロパティはありません。
DbMigrator も試しましたが、いくつかの内部 EF 移行メソッドを呼び出します。
DbMigration.Up メソッドで使用される接続を設定する方法を知っている人はいますか?
前もって感謝します!
次のコードを使用して、Application_Start イベントでデータベースを明示的にアップグレードできるようにします。
var config = new MyDatabaseMigrationsConfiguration();
var migrator = new System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator(new System.Data.Entity.Migrations.DbMigrator(config), new MyCommonMigrationsLogger());
if (migrator.GetPendingMigrations().Any())
{
migrator.Update();
}
私の知る限り、これは保留中の変更を適用するために、私の DatabaseContext からのデフォルトの(名前付きの)接続文字列を使用します。
移行を完全に手動で制御するには、次の拡張メソッドを使用できます。
public static void RunMigration(this DbContext context, DbMigration migration)
{
var prop = migration.GetType().GetProperty("Operations", BindingFlags.NonPublic | BindingFlags.Instance);
if (prop != null)
{
IEnumerable<MigrationOperation> operations = prop.GetValue(migration) as IEnumerable<MigrationOperation>;
var generator = new SqlServerMigrationSqlGenerator();
var statements = generator.Generate(operations, "2008");
foreach (MigrationStatement item in statements)
context.Database.ExecuteSqlCommand(item.Sql);
}
}
例: 次のような移行があります。
public class CreateIndexOnContactCodeMigration : DbMigration
{
public override void Up()
{
this.CreateIndex("Contacts", "Code");
}
public override void Down()
{
base.Down();
this.DropIndex("Contacts", "Code");
}
}
DbContext に対して実行できます。
using (var dbCrm = new CrmDbContext(connectionString))
{
var migration = new CreateIndexOnContactCodeMigration();
migration.Up(); // or migration.Down();
dbCrm.RunMigration(migration);
}