[Code First] Migrations

Your DB will not stay the same. When using CodeFirst, you need to update DB from code. This update is the biggest hassle in Code First. One way of updating DB is “Code First Migration“. It is done by “Package Manager Console“.

 

1. Enabling Migration

Open the “Package Manager Console“. It is a PowerShell command shell.

PM> Enable-Migrations

PM> Enable-Migrations -ContextTypeName MyProject.ProductContext

In order to use the “automatic” migration, use the “-EnableAutomaticMigrations” option.

 

2. Configuring Migration

The “Migrations” folder is created and you can find the following file:

  • Configuration.cs

The “Configuration” class is derived from “DbMigrationConfiguration“.

internal sealed class Configuration
    : DbMigrationsConfiguration<ProductContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = false;
    }

    protected override void Seed(ProductContext context)
    {
    }
}

 

3. Automatic Migration

You can enable the “automatic” migration by setting the “AutomaticMigrationsEnabled” property to true.

public Configuration()
{
   AutomaticMigrationsEnabled = true;
}

 

4. Seeding Data

You can override the “Seed()” method in the “Configuration” class if you want initial data.

  • Use “DbSet.AddOrUpdate()” method instead of “Add()“.
protected override void Seed(ProductContext context)
{
    context.Products.AddOrUpdate(
        d => d.Name,
        new Product { Name = "P1" },
        new Product { Name = "P2" },
        new Product { Name = "P3" }
    );
}

Note that there is no id for seed data yet. So you need to provide the unique key as a first parameter.

 

5. Initializing Databases

The create a database, run the following command in the “Package Manager Console“.

PM> Add-Migration Initial

The “xxxxxx_InitialCreate.cs” file is created in the “Migrations” folder. It contains the instructions to create a database. This does not create the database yet.

 

6. Updating Databases

To update (or create) the database, you can do it in the “Package Manager Console“.

PM> Update-Database

PM> Update-Database -Verbose

PM> Update-Database -Verbose -Force

 

7. Setting the Database Initializer

Before migration, there are 3 choices of database initialization:

  • CreateDatabaseIfNotExists – default
  • DropCreateDatabaseIfModelChanges
  • DropCreateDatabaseAlways

They implement the “IDatabaseInitializer” interface. For migration scenarios, a new “MigrateDatabaseToLatestVersion” initializer is introduced.

protected void Application_Start()
{
    Database.SetInitializer<ProductContext>(
        new MigrateDatabaseToLatestVersion<ProductContext, GlobalConfiguration>());
}

 

8. Modifying the Database Schema

The core step of migration is modifing the database. Suppose you add a new column “Cost” to the “Product” table.

  • Modify the model class
  • Modify the controller and views
  • Modify the Seed() method if necessary

After changing the code, you can specify the migration point.

PM> Add-Migration ProductCost

The “xxxxxx_ProductCost.cs” file is created in the “Migrations” folder.

Finally you can update the database.

PM> Update-Database

 

9. Multiple Migrations (EF6)

PM> Enable-Migrations -ContextTypeName AccountDb -MigrationsDirectory MigrationsIdentity
PM> Enable-Migrations -ContextTypeName ContosoDb -MigrationsDirectory MigrationsContoso
PM> Add-Migration -ConfigurationTypeName ContosoData.Migrations.Contoso.Configuration “Init”
PM> Update-Database -ConfigurationTypeName ContosoData.Migrations.Identity.Configuration
PM> Update-Database -ConfigurationTypeName ContosoData.Migrations.Contoso.Configuration

 

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s