使用FluentMigrator迁移数据

时间:2015-11-13 08:47:00

标签: c# fluent-migrator

我在项目中使用FluentMigrator。 现在我在表中添加新列以及如何通过SQL查询更新此列中的数据?

public override void Up()
{
    Alter.Table("Images").AddColumn("Item_id").AsInt32().Nullable();
    //do something like "Update Images img set img.Item_id=(Select i.Id 
    //from Items i where i.Image=img.Id)"
}
public override void Down()
{
    Delete.Column("Item_id").FromTable("Images");
}

2 个答案:

答案 0 :(得分:0)

您可以使用Insert.IntoTable

Insert.IntoTable("Users").Row(new { Username = "CURRENT_USER" });

Execute.WithConnection使用FluentMigrator

插入数据

答案 1 :(得分:0)

嗨,我相信您可以简化您的案件,但我遇到了一个更复杂的问题。我添加了一个新的varbinary类型的列,在该列中,我需要保留一个复杂的对象,并且需要用c#代码进行准备。所以我不能只执行与SELECT命令结合的UPDATE。

我通过在执行SQL SELECT命令的地方添加一个静态类解决了这一问题,然后在迁移过程中使用检索到的数据来准备UPDATE命令。

重要的线索是使用可从FluentMigrator.Migration类直接访问的ConnectionString并执行自己的SQL命令以获取数据,然后在C#中对其进行处理,然后简单地使用FluentMigrator的Update.Table方法。

这是我的代码(简体):

DatabaseHelper类:

/// <summary>
/// Helper class for executing SQL on a Database defined by given ConnectionString
/// </summary>
public static class DatabaseHelper
{
    /// <summary>
    /// Run SQL SELECT on a Database defined by given ConnectionString
    /// </summary>
    /// <param name="connectionString">Connection string</param>
    /// <param name="sql">Full SQL SELECT command to be executed</param>
    /// <returns>List of rows containing all columns as string[] array</returns>
    public static string[][] SelectList(string connectionString, string sql)
    {

        using (SqlConnection sqlConnection = new SqlConnection($"{connectionString}"))
        {
            try
            {
                sqlConnection.Open();

                SqlCommand command = new SqlCommand(sql, sqlConnection);
                SqlDataReader reader = command.ExecuteReader();

                if (!reader.HasRows)
                    return null;

                List<string[]> rowsList = new List<string[]>();

                //save all rows (including all columns) from the response to the list
                while (reader.Read())
                {
                    //every row has n columns
                    var row = new string[reader.FieldCount];

                    //fill every column
                    for (int i = 0; i < reader.FieldCount; i++)
                    {
                        row[i] = reader[i].ToString();
                    }

                    //add row to the list
                    rowsList.Add(row);
                }

                reader.Close();
                sqlConnection.Close();

                return rowsList.ToArray();
            }
            catch (Exception e)
            {
                if (sqlConnection.State == ConnectionState.Open)
                    sqlConnection.Close();

                Console.WriteLine(e);
                throw;
            }
        }
    }
}

迁移类:

public class Migration123 : Migration
{
    public override void Up()
    {
        Create.Column("NEW_COLUMN").OnTable("TABLE_NAME").AsCustom("NVARCHAR(255)").Nullable()

        //migrate data from OLD_COLUMN to NEW_COLUMN
        MigrateData();

        ...

    }

    private void MigrateData()
    {
        string[][] rowsArray = DatabaseHelper.SelectList(ConnectionString,"SELECT [ID],[OLD_COLUMN] FROM [TABLE_NAME]");

        //if nothing to migrate then exit
        if (rowsArray == null)
            return;

        foreach (var row in rowsArray)
        {
            //prepare a value which will be inserted into a new column, basing on old columns value
            var someNewValueForNewColumn = row[1] + " (modified)";

            //insert a value into a new column
            Update.Table("TABLE_NAME").Set(new
            {
                NEW_COLUMN = someNewValueForNewColumn 
            }).Where(new
            {
                ID = row[0]
            });
        }
    }

    public override void Down()
    {
        ...
    }
}

希望对您有所帮助!