DEV Community

Akash Kava
Akash Kava

Posted on

EF Core Auto Migration with No Data Loss

EF Core has dropped support for Auto Migration, which is very useful in prototyping applications. Migration support is too laborious in EF Core.

Introducing EF-Core-Live-Migration

Features

  1. Creates Missing Table
  2. Creates Missing Columns
  3. If column already exists and if data type is different, then old column is renamed and new column column will be created with transfer of data from old, transfer can be lossy,
  4. Renames old indiexes and creates new ones
  5. Creates indexes based on foreign keys

Installation

PM>Install-Package NeroSpeech.EFCoreLiveMigration

Configure

public void Configure(IApplicationBuilder app, IHostingEnvironment env){

    if(env.IsDevelopment()){
        app.UseDeveloperExceptionPage();

        using (var scope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
        {
            using (var db = scope.ServiceProvider.GetRequiredService<AppModelContext>())
            {
                MigrationHelper.ForSqlServer(db).Migrate();
            }
        }
    }

}

Limitations

Works only with SQL Server right now.

Old Name Attribute

If you decide to rename a column, you can mark the property with [OldName("name")], so while migration, it will rename existing column if there is no data loss. In case of data loss, existing column will be saved as other column and data will be transferred to new column.

Help Wanted

The API was written without Migration API introduced later in EF Core. I need help in rewriting API with Migration API so it can be used with any backend.

Top comments (0)