4

我有一个特定的数据库脚本需要作为最后一个迁移脚本运行,并且每次我在数据库上运行迁移时都需要运行它(即使它之前已经运行过)。

我可以使用非常大的迁移 ID 来确保此迁移最后运行。但是,我不知道如何强制每次重新运行此迁移:一旦运行,它就会被添加到dbo.VersionInfo表中,并且下次 FluentMigrator 在该表中看到它时,它不会再次运行它。

[Migration ( 209912312359 )]
public class M209912312359 : Migration
{
    public override void Down ()
    {
        // I want this particular migration to always run
        // as the last migration script and to run every time.
    }
}

是否有某种迁移属性告诉 FluentMigrator 每次都运行此脚本,而不管以前的运行如何?(Migration基类对此没有任何可覆盖的内容。)

我正在使用 FluentMigrator 1.4。

编辑:

这是一个数据迁移,清理数据库中的一些数据。在工作中,我们有大量的数据库(相同的模式,不同的数据)。一个特定的表(我们称之为它dbo.A)必须在所有数据库中以相同的顺序具有相同的数据。我们使用迁移将数据添加到此表,但有时 - 根据特定数据库中运行的迁移 - 实例dbo.A可能会不同步。

此迁移的目的是确保 的所有实例以dbo.A相同的顺序包含相同的数据。我们不能删除dbo.A并重新创建它,因为它的ID列被用作外键。

如果可能的话,我希望有一个迁移解决方案,因为迁移是唯一保证在我们所有环境中作为部署的一部分运行的东西,而改变它会非常困难。(如果 FluentMigrator 不能做到这一点,我们可能别无选择。)

4

3 回答 3

5

只需使用如下[Maintenance(MigrationStage.AfterAll)]属性,它将始终运行该Up()方法:

using FluentMigrator;
using System;

namespace Example
{
    [Maintenance(MigrationStage.AfterAll)]
    public class RefreshAllViews : FluentMigrator.Migration
    {
        public override void Up()
        {
            Execute.Sql(@"
                DECLARE views_cursor CURSOR FOR
                SELECT name FROM sysobjects WHERE type = 'V' AND uid = 1
                OPEN views_cursor

                DECLARE @view NVARCHAR(500)
                FETCH NEXT FROM views_cursor INTO @view
                WHILE @@FETCH_STATUS = 0
                BEGIN
                    BEGIN TRY
                        EXEC sp_refreshview @view
                    END TRY
                    BEGIN CATCH
                        PRINT 'VIEW NAME: ' + @view + 
                              ', ERROR NUMBER: ' + Cast(ERROR_NUMBER() as VARCHAR) + 
                              ', ERROR MESSAGE: ' + ERROR_MESSAGE()
                    END CATCH
    
                    FETCH NEXT FROM views_cursor INTO @view
                END

                CLOSE views_cursor
                DEALLOCATE views_cursor");
        }

        public override void Down()
        {
            throw new NotImplementedException();
        }
    }
}
于 2018-08-09T02:20:22.567 回答
2

为了解决您的问题,我刚刚创建了一个抽象类,该类实现方法 Down 并在您的新迁移类上继承它。

public abstract class MigrationBase : FluentMigrator.Migration
{
    public override void Down()
    {
        //Do what you want for every migration
    }
}

[FluentMigrator.Migration(209912312359)]
public class M209912312359 : MigrationBase
{
    public override void Up()
    {
        //New migration...
    }
}
于 2016-01-20T12:03:23.097 回答
1

似乎您必须使用 MaintenanceAttribute 或使用 Execute.Sql 命令执行其他操作,它会从 VersionInfo 表中删除迁移记录。

于 2016-06-09T22:15:25.167 回答