In a past blog I have explained some new features within the Entity Framework and I differentiated between two specific approaches provided within the Entity framework spectrum, Code First and Model First. Since then alot of new features were introduced within the Entity Framework including the Fluent API and more importantly Database Migrations. Traditionally when you build a web application and create your data layer using Entity Framework as your ORM, you would set a Database Initalizer with one of the following configuration strategies:

  • CreateDatabaseIfNotExist: This is typically the deafault Database initalizer and will create a new database from your model configuration if no database is found for your configured connection string.
  • DropCreateDatabaseIfModelChanges: This initializer will only create a new database either when no database exists or when a change has been done to the model. This configuration is usually suitable during the development stages as you would have a clean fresh database model whenever you change somthing within your data models.
  • DropCreateDtabaseAlways: As the name states, this initializer will drop the database and create a new one everytime it s run. This model is also typically used during development however it might make your debugging process a bit slow especially if you have a large complex database model.
  • Custom DB Initializer: You can customize your initalizer to instruct Entity Framework what to do everytime the application is initalized.

Database initializers may be able to get the job done while we're developing our application for the first time, but what happens after we roll out and we want to update our data models? Will we loose all our data? Before database migrations we used to make use of schema comparison tools available within Visual Studio to get update scripts we should apply to our databases in order to update our schemas accordingly. More information on how to user Schema Comparison tools provided within Visual Studio can be found here.

Database migrations give you a way out both when you're working within a team enviroment and when you want to update a schema for a deployed web site and you don't want to loose your data and this can all be done through the package manager console using a few common commands.

Lets go through the steps involved in enabling database migrations to our project and actually apply the generated database migrations. I'm going to explain the process in a number of steps and I will add some comments where neccessary to explain better what Entity Framework is doing behind the scenes.

1) INSTALL ENTITY FRAMEWORK

This is quite a trival step but its always worth mentioning that before you expect your package manager console to understand what the Database migration commands mean, you need to install the entity framework. The following commands allow you to do this easily through the package management console (Tools -> Library Package Manager -> Package Manager Console)

PM> Install-Package EntityFramework

This will install the latest version of Entity Framework to your selected project. On a special note, make sure you select the project you want the Entity Framework installed to as if you don't, it will be installed to your default project within the solution.

2)ENABLE MIGRATIONS

This is the second step in using Code First database migrations. This step will allow the Package Manager Console to install the Databse Migration Configuration File to your data project. It will also create the Databse Migrations Folder where all databse migration classes will be generated when neccessary. In order to Enable Databse Migrations to your project, you should run the following command:

 

enable-migrations

This specific commands takes a couple of paramteres which are also worth mentioning:

  • ContextTypeName (used when you have multiple databse contexts)
  • Migrations Directory (used to specify the directory for your database migration files)

 

enable-migrations -ContextTypeName MyFirstContext -MigrationsDirectory MyFirstMigrations

3) Add Migration

After enabling migrations, Enity Framework takes a snapshot of your database model. Whenever you do some updated to your model such as removing a property or changing the name of a property or adding a new entity, this is the command you must remember to run:

Add-Migration AddingPersonAge

This command will instruct Entity Framework to go through your database models and scaffold all the changes it identifies into a new migration cs file. The cs file is not executed automatically but is places in the same location as the configuration file for your specific databse context.

This specific command also takes a couple of parameters:

  • ProjectName
  • ConfigurationTypeName
Add-Migration -Name MyFirstMigration -ProjectName MyFirstMigrationProject
Add-Migration -Name MyFirstMigration -ConfigurationTypeName MyFirstNameSpace.Configuration

 4) Update Database

This is the most important command there is. This command will get the current database migrations which have not been applied to your model yet and execute them. This will allow you to get the latest schema model changes applied to your database. As you might have guessed, yes this method has a number of parameters which you can specify:

  • ProjectName 
  • ConfigurationTypeName (multiple DBContext can be seperated by diff configs)
  • TargetMigration (if you want a specific migration to be executed and not neccessarily the last one)
  • Script (if you want database migrations to generate a script for you so that you can run it on your production database)
  • SourceMigration (used when generating a script from one migration to another)
Update-database -TargetMigration AddingPersonAge
Update-database -Script -SourceMigration AddingPersonAge

 5) Get Migrations

 The get migrations command is used to get a list of all the migrations currently applied to the database. This can be used within a team enviroment where members want to verify which migrations have been applied and which are still pending.

Thats it! Those are the commands you need to keep in mind when using Entity framework database migrations. Another cool feature within database migrations are the automatic migrations. I will explain this difference better in the coming section.

Code Based vs Automatic

Code First Datbase migrations come into two flavours:

  1. Code Based Migrations
  2. Automatic Migrations

Both of the migrations have their own uses. As the name suggests automatic migrations practically allows Entity Framework to monitor your model changes and create the necessary migrations. Whenever you want the changes to be applied to your database schema, you just call the update-database command and the changes are automatically applied. 

Basically Automatic Migrations make sure that whenever you call the update-database command, you will be getting all the changes currently applied to a model. Note, not all changes can be done through automatic migrations. Changes to column names for example still need a code-based migration. 

I personally prefer code based migrations as I want to see and keep track of all the migration scripts generated by Entity Framework for my database model. This would give me more control as to which migrations to apply and when especially on my live enviroments where I usually prefer the use of scipts to make sure that changes will run smoothly.

Well, that is all from me for today, I hope you'll make use of this cool feature within the Entity Framework and I hope it saves you some time when making changes to your data models.

Thank you for reading,

Shaun