We´ve changed some logic in our application and now we add some fields within a migration but the existing entries should get some values also. Therefor we need to load the entry, calculate some values and need to add this value to the new field. So how to access the data which is requested with the Sql-Method
? The defaultValue-Flag of the AddColumn-Method will not work because every entry has a value calculated different.
Here somekind of workflow:
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<uint>(
name: "Field",
table: "Table",
type: "INTEGER",
nullable: false,
defaultValue: 0u);
var builder = migrationBuilder.Sql("SELECT * FROM Table");
var data = builder.AccessData; // here I´m unsure how to access the data
data.Field = Calculator(data);
migrationBuilder.UpdateData(data); // this one is also not cleare
}
CodePudding user response:
A MigrationBuilder
is a way to express in a fluent, C#-friendly fashion the SQL code that will be executed during the migration itself. Even if the code you write and the "intermediate files" generated by the migration tool look as C#, at the end the migration becomes pure SQL that neither knows nor can communicate with your application.
Therefore, if you need to process existing data, all your logic must happen DB-side and must be expressed as operations on the MigrationBuilder
. Of course in the Up
and Down
methods of the migration you can leverage all the power of C# to build the raw SQL statements to be provided to the migrationBuilder.Sql(...)
. Also, consider that the whole migration is executed in a transaction and that a "volatile" stored procedure can turn out to be useful to extract a complex migration logic.