简体   繁体   中英

Entity Framework Data Migration

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
    }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM