Migration in EF Code First

|
| By Webner

Code First Conventions

In code first approach we create the domain classes first rather than creating the database. Initially, we need to create the domain classes having the properties and then we create the database according to the domain classes.
code first
Database Migration – Migration is used to update the database schema as our domain classes change.

There are 2 ways to do the migration in code first –
1.Code-based Migration
2.Automated Migration

Code-based Migration

For code migration, we need to use the following commands in the Nuget Package manager console in visual studio –

  1. Enable-migration – This command enables the migration for our project by creating the Migration folder and Configuration class.
  2. Add-migration – It adds all the changes in the models in the up and down functions in the new migration file. Syntax is add-migration <file name>. This command will create a new file with <timestamp>_<file name>.cs
  3. Update-database – This command will execute the last migration created by the add-migration command.

Up and down functions in the migration file

The Up() function contains the code for creating the database and Down() function contains the code for dropping or deleting the database objects.

For help with any command, we can execute a command get-help <command name>
Rollback Migration – If we want to rollback our database schema to any previous migration state then we can use the update-database command with the -TargetMigration parameter.

update-database -TargetMigration:<migration file name>

If we want to see the SQL statements our migration process applied to the database, we can use -verbose parameter with the update-database

Update-database -Verbose

Automated Migration – In this type of migration we don’t have to process the migration manually for every change. We can enable the automatic migration through the following command –

enable-migrations –EnableAutomaticMigration:$true

This command will set the AutomaticMigrationsEnabled to true in the Configuration class.

The next step is to the database initializer in the context class to MigrateDatabaseToLatestVersion

public class SchoolContext: DbContext
{
public SchoolDBContext(): base("SchoolDB")
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<SchoolDBContext, EF6 Console.Migrations.Configuration>());
}
public DbSet<Student> Students { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}

migration code

Here is the screenshot of the Migration folder structure. We can see that the Migration folder has the Configuration file in which we can configure the settings for migration like whether we need to enable automatic migration or not.

This folder also contains all the migration files that are created during the add-migration command.

Leave a Reply

Your email address will not be published. Required fields are marked *