C#从代码自动迁移中的自定义迁移?

时间:2017-05-29 08:43:08

标签: c# entity-framework

我在开始应用程序时运行所有迁移,如下所示:

            var configuration = new DbMigrationsConfiguration<MyContext>
            {
                TargetDatabase = new DbConnectionInfo("DataBase"),
                AutomaticMigrationsEnabled = true,
                AutomaticMigrationDataLossAllowed = true
            };

            _migrator = new DbMigrator(configuration);
            _migrator.Update();

并且有一些代码优先的上下文:

public class MyContext : DbContext
{
    public DbSet<MyObject> Objects { get; set; }
}

public class MyObject
{
    public long Id {get;set;}

    public byte[] Data {get;set;}
}

并未使用任何预生成(使用EF工具)迁移。起初就足够了,但现在我需要为数据库运行一些自定义SQL代码以迁移到最新版本。例如,这一个:

public class MyCustomMigration : DbMigration
{
    public override void Up()
    {
        Sql(@"
            CREATE TABLE Files
            (
                Id BIGINT IDENTITY PRIMARY KEY,
                Data VARBINARY(MAX) FILESTREAM
            )
        ");
    }

    public override void Down()
    {
        DropTable("Files");
    }
}

我如何完成这项任务?我尝试在配置中设置迁移目录,但没有成功(没有任何反应,迁移不受影响)。

1 个答案:

答案 0 :(得分:0)

为什么不能通过包管理器控制台使用内置的迁移管理?

enable-migrations (make sure you have the right project selected - creates a 
                    migrations directory)
add-migration MyFirstMigration
update-database

每次在上下文中更改DbSets中的模型后,都需要手动执行此操作。但是这样它会为您生成所有迁移Sql,并使用种子方法创建一个Configuration类,您可以在运行时使用该方法更新新模式:

update-database