in c#

ORM Series : Entity Framework Migration

Entity Framework, has given with last update, migrations at code first, undoubtedly it’s the best feature in this update. This tool is very helpful if we change something at our model, and then we can simply upgrade our database. Moreover it can fulfill role as a database versioning, because we can easily to manage our updates and freely manage between them.

Whole system is based on Package Manager Console. Basic commands

  • Enable-Migrations
  • Add-Migration {name of commit}
  • Update-Database

Enable-Migration we are using only once. It’s command which create basic files need to start work with migrations. Add-Migration is command we will use if we want to add some changes to database, and it generate file with . Update-Database – execute migrations files

First we have to create our model, I created simple music database:

 

 

 

Now we will run our Packer Manager Console with Enable-Migrations command.

If executed command was properly , we will see ‘Migrations’ folder.

image

Now we can execute next command, Add-Migration BaseOfDatabase. ‘BaseOfDatabase’ is name of commit so choose wisely because it should describe in one – two words what you have done here. Moreover there is a new generated file.

image1

That file include code that will be executed at final step, code sample one from few methods.

 

Now we can execute all of updates. By using Update-Database command. If everything goes properly, let’s change our model to show you, power of Migrations.

Album.cs

Song.cs

Let’s now commit our changes, execute Add-Migration command, result of execution

Update database, our database has given these two columns. Now we can freely downgrade or upgrade our version of database. 🙂 so if we decided after thousands of commit to delete these columns

Score : For this feature I will give EF two stars in category “Uniqueness”
summary_sec

  • http://www.mfranc.com/ Michal Franc

    And i assume that there are no features like this in NHibernate ? Also is the data “save” while migrating ? I mean is it copied to new table schema.

    • http://pawel.sawicz.eu/ Pawel Sawicz

      Yea, if we Update our database this not cause drop-table, and create new one. Just adds in eg. new column like if you are using MSSQL Designer.

  • Pingback: Entity Framework – reset migrations | Pawel Sawicz .NET blog