C# 使用FluentMigrator迁移数据

C# 使用FluentMigrator迁移数据,c#,fluent-migrator,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

我在项目中使用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");
}
您可以使用:


或者使用FluentMigrator执行。WithConnection插入数据。您好,我相信您可以简化您的案例,但我遇到了一个更复杂的问题。我添加了一个varbinary类型的新列,在这里我需要保留一个复杂的对象,并且需要用c代码准备它。所以我不能只执行UPDATE和SELECT命令

我通过添加一个静态类来解决这个问题,在该类中执行SQLSELECT命令,然后在迁移过程中使用检索到的数据来准备更新命令

重要的线索是使用ConnectionString,它可以直接从FluentMigrator.Migration类访问,并执行自己的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;
            }
        }
    }
}

希望它能帮助别人

Insert.IntoTable是插入新行。我想使用另一个表中的数据更新现有行。Execute.WithConnection不工作,因为它没有上下文,并且NHibernate无法通过连接字符串Data Source=| DataDirectory | db.db3找到数据库;版本=3;你说的是Nhibernate还是schambers FluentMigrator?对不起。FluentMigrator你说的是schambers FluentMigrator,不是Nhibernates,对吧?如果是这样,我将删除标记并编辑标题{var command=dbConnection.CreateCommand;command.CommandText=@Update Images set Images.Item_id=Select Items.id from Items.Image_id=Images.id;command.ExecuteNonQuery;}并获取FM找不到DB的错误
/// <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()
    {
        ...
    }
}