2014-08-29 53 views
0

让说我有定义的随机码第一迁移类:实体框架代码首先:触发特定迁移

public partial class t2 : DbMigration 
{ 
    public override void Up() 
    { 
     RenameTable(name: "dbo.EntityC", newName: "EntityCs"); 
     DropTable("dbo.EntityA"); 
     DropTable("dbo.EntityB"); 
    } 

    public override void Down() 
    { 
     CreateTable(
      "dbo.EntityB", 
      c => new 
       { 
        Id = c.Int(nullable: false, identity: true), 
        StringOtherProperty = c.String(), 
       }) 
      .PrimaryKey(t => t.Id); 

     CreateTable(
      "dbo.EntityA", 
      c => new 
       { 
        Id = c.Int(nullable: false, identity: true), 
        StringProperty = c.String(), 
       }) 
      .PrimaryKey(t => t.Id); 

     RenameTable(name: "dbo.EntityCs", newName: "EntityC"); 
    } 
} 

我如何执行它,不管当前的数据模型。 我可以通过代码或PowerShell强制执行此迁移吗?

回答

1

迁移始终与底层的上下文和模型有关。这基本上是__MigrationHistory表的内容。

所以使用默认的DbMigrator,不可能在没有Context的情况下执行migraton。

但您可以使用Reflection从您的自定义迁移中获取内部“操作”属性,将其手动传递给MigrationSqlGenerator并手动执行语句。

SqlServerMigrationSqlGenerator gen = new SqlServerMigrationSqlGenerator(); 
IEnumerable<MigrationOperation> operations; 

var migration = new MyMigration(); 
migration.Up(); 

var property = typeof(DbMigration) 
    .GetProperty("Operations", BindingFlags.Instance | BindingFlags.NonPublic); 

operations = property.GetGetMethod(true) 
    .Invoke(migration, null) as IEnumerable<MigrationOperation>; 

if (operations != null) { 
    var statements = gen.Generate(operations, "2012"); 

    using (var scope = new TransactionScope()) { 
     var connection = new SqlConnection("Data Source=.;Initial Catalog=MigrationTest;Integrated Security=True;"); 
     connection.Open(); 
     foreach (var item in statements) { 
      var command = connection.CreateCommand(); 
      command.CommandText = item.Sql; 
      command.ExecuteNonQuery(); 
     } 
     scope.Complete(); 
    } 
}