0
votes

I use FluentMigrator in my project. And now I Add new column in table and how I can update data in this column by SQL query?

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

2 Answers

0
votes

You can either use Insert.IntoTable:

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

or Execute.WithConnectionto insert data using FluentMigrator

0
votes

Hi I believe You can make it simpler for Your case, but I had a more complex issue. I added a new column of varbinary type, where I needed to keep a complex object and I needed to prepare it in c# code. So I couldn't just execute UPDATE combined with SELECT command.

I solved that by adding a static class where I execute SQL SELECT command, then I use retrieved data during migration to prepare UPDATE commands.

The important clue is to use ConnectionString which is accessible directly from FluentMigrator.Migration class and execute own SQL commands to get data, then process it in C# and then simply use Update.Table method of FluentMigrator.

Here is my code (simplified):

DatabaseHelper class:

/// <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;
            }
        }
    }
}

Migration class:

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()
    {
        ...
    }
}

Hope it helps somebody!