So Su Team : Web Development Tags : Technology Web Development

Code First Migrations

So Su Team : Web Development Tags : Technology Web Development

Code first is an approach where you define your data models in code, and allow Entity Framework to generate the database schema for you. A code first migration is the mechanism by which a developer can update their database schema when their code model changes.

Historically this was a very painful process. I recall on its initial release, it was easier to drop the database and allow the framework to regenerate the entire schema again from scratch. You can imagine how annoying this would be if you had a thousands of rows of test data in there. But it’s a lot better now, and it’s a lot easier to generate migration scripts as well, saving you from blowing away all that test data. The migration is still not perfect, so you have to check the code generated every time before running against a database.

A while back, a colleague asked about code first migration and I couldn’t recall the commands for it. So here they are. Run these commands in the Package Manager Console in Visual Studio, make sure your data project is selected as the target project from the drop down, and make sure the app.config or web.config connection string is pointing to an actual database.

 

Enable Migrations

Enable-Migrations

Run this command to enable code first migrations. It will generate a Migrations folder in your data project and an InitialCreate script that defines the data model.

 

Adding a migration

Add-Migration {name}

Run this command to add an update to the list of migrations. Before you do this, make sure your database is up to date, that all the pending migrations have been run against it already. Specify a {name} for the migration, something meaningful not just a date/time stamp.

 

Updating the database

Update-Database –TargetMigration: {name} -Script

Run this command to update or rollback the database to a given point. Provide the {name} given when the add migration command was run. The “-Script” parameter will generate a SQL script, and not actually perform a database update. Remember when I said this wasn’t perfect. Well you ALWAYS want to double check the SQL Entity Framework will run for any migration, and “-Script” will allow you to do that.

You can find more info on MSDN, including some very useful examples.