Code First Data Migrations

These are run from Package Manger Console. They assume that you have a database in SQL Express named the fully qualified name of your context class, so make sure you have put a copy of your database there and you named it ‘MyNameSpace.MyEntityContext’ (where MyEntityContext is your DBContext’s class name).

Now in Package Manager Console:

Uses models referred to in dbContext

Enable-Migrations  (only needs to be run once on project and it sets up the folders and config files)


If you are wanting to start with an existing database you need to baseline your migration scripts with this:

Add-Migration IntialCreate -IgnoreChanges (this creates an empty script)

Then run:

Update-Database (this will create the __MigrationsHistory table, and run your empy script as a baseline point)

Now you can add new models…

Next you can run Add-Migration for your changes as follows.


Add-Migration nameOfMigration (the first time this runs it generates scaffold and migration, and a resource file, which can be used to push migration to database)

-Now you change the models in code and then

Add-Migration secondMigration (this scaffolds the update to database)

Update-Database  (pushes the changes to the database) (your models appear in database and the _MigrationHitory table gets updated)

Get-Migrations (will list all the migrations run to this point on that database by reading the _MigrationHistory table)

Update-Database -targetMigration: “[migrationName]”  (where “MigrationName” is one of the items listed in the Get-Migration results, and you do need the quote markes)


-Make some model changes in code


Add-Migration theNameOfMyMigration (This will figure out the diff of current model and last migration and create the new Migration process)

Update-Database  (pushes the changes to the database) (your models appear in database and the _MigrationHitory table gets updated)



Leave a Reply

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

You are commenting using your 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