Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Core 2.1, rename table using code-first migrations without dropping and creating new table

I'm using netcoreapp 2.1 with EF Core 2.1 and updating my database with data migrations and have come into a problem with renaming tables. My main issue here is a table (and later potentially columns) may be renamed multiple times with data and I want to be able to rename them while keeping this data intact but from what I've read it seems these migrations only seem concerned with keeping the schema up to date.

This issue is similar to Change or rename a column name without losing data with Entity Framework Core 2.0 but as my process is automated I need to be able to do this using the migration itself on the command line with dotnet.exe.

To do this I am passing the argument below to dotnet.exe, building the solution, getting the DB context from the DLL and then running the migration with the lines below that.

ef migrations add "someMigrationName"

...and to update database

var migrator = dbContext.Database.GetService<IMigrator>();
migrator.Migrate();

As an example, if a table named "Courases" starts collecting data I need to be able to rename it "Courses" without it affecting the data however currently the below is the generated Up function in the migration.

protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.DropTable(
            name: "Courases");

        migrationBuilder.CreateTable(
            name: "Courses",
            columns: table => new
            {
                Id = table.Column<Guid>(nullable: false),
                ConcurrencyCheck = table.Column<byte[]>(nullable: true)
            },
            constraints: table =>
            {
                table.PrimaryKey("PK_Courses", x => x.Id);
            });

    }

From what I've read there seems to be no way to generate a migration with tables renamed rather than dropped and recreated but this seems crazy, is there a way of doing this/is there a flag I can pass to dotnet.exe that I've missed?

like image 388
James Morrison Avatar asked Jul 26 '18 08:07

James Morrison


People also ask

How do I update the table schema in Entity Framework?

Drop and Recreate Your Database You can configure Entity Framework to delete (drop) and recreate your database every time there is a change to your schema. To do this, you need to create an initializer class in the same folder as your DbContext class. The class needs to inherit from DropCreateDatabaseIfModelChanges .


1 Answers

Check out https://docs.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.migrations.migrationbuilder.renametable?view=efcore-2.1

You can just call migrationBuilder.RenameTable("Old", null, "New");

like image 62
Tom McClean Avatar answered Sep 22 '22 01:09

Tom McClean