Change or rename a column name without losing data with Entity Framework Core 2.0

后端 未结 2 1373
故里飘歌
故里飘歌 2021-02-19 03:14

I realised that I had spelt one of my column headers incorrectly so I changed it in the model and created a new migration to update it into the database. All worked perfectly un

相关标签:
2条回答
  • 2021-02-19 03:25

    migrationBuilder.RenameColumn usually works fine but sometimes you have to handle indexes as well.

    migrationBuilder.RenameColumn(name: "Identifier", table: "Questions", newName: "ChangedIdentifier", schema: "dbo");
    

    Example error message when updating database:

    Microsoft.Data.SqlClient.SqlException (0x80131904): The index 'IX_Questions_Identifier' is dependent on column 'Identifier'.

    The index 'IX_Questions_Identifier' is dependent on column 'Identifier'.

    RENAME COLUMN Identifier failed because one or more objects access this column.

    In this case you have to do the rename like this:

    migrationBuilder.DropIndex(
        name: "IX_Questions_Identifier",
        table: "Questions");
    
    migrationBuilder.RenameColumn(name: "Identifier", table: "Questions", newName: "ChangedIdentifier", schema: "dbo");
    
    migrationBuilder.CreateIndex(
        name: "IX_Questions_ChangedIdentifier",
        table: "Questions",
        column: "ChangedIdentifier",
        unique: true,
        filter: "[ChangedIdentifier] IS NOT NULL");
    
    0 讨论(0)
  • 2021-02-19 03:38

    EF Core creates its migrations by comparing your models to the current database snapshot (a c# class). It then uses this to create a migration file you can review. If EF Core cannot always know if you replaced this column or created a new column. When you check your migration file, make sure there are no column drops, index drops (related to this column) etc. You can replace all these with something like this:

    migrationBuilder.RenameColumn(
        name: "ColumnA",
        table: "MyTable",
        newName: "ColumnB");
    
    0 讨论(0)
提交回复
热议问题