For programmers, testers and tech geeks

Asp.net MVC4 database migrations with Entity Framework

Hi all, in this post I am going to talk about database migrations and how you can use it in your project and why should you use that feature. In Asp.net MVC Code first approach we use to create our model (entities and their associations) first and define our context class which contains the list of these entities implementing DBContext class. So when we change our code for any entity add or update case and run the application then an error screen comes which says your model is been updated, which means that to get rid of this error we must have to delete our old database and run our application again which will create new database for us with updated tables and what if we have thousands of records and we have any change in our model then?
In order to escape from this database deletion and creation process again and again we use database migrations.
Yes this is the way a developer can update its models without effecting the database data, actually migration works on context, it just picks all changes and create migration file and update changes on single command. To take advantage of migrations you just need to know about 3 commands:
 
1)  First step is open your project in Visual studio , go to Tools->Library Package Manager->Package Manager Console and click it , this will open a console with "PM> " as initials. Now first select the project which contains the context class as default project in this console. Then install or update EntityFramework package into your project with these commands:

  1. PM>Install-Package EntityFramework Or
  2. PM>Update-Package EntityFramework
After that enable migrations in your selected project with this command:
  • PM>Enable-Migrations
2) Now your setup is ready for starting the migrations, Enabling migrations will create Migrations folder into your project with Configuration.cs class and all future migrations will be automatically added into this folder.
Now update your models and run add migration command:
  • PM> Add-Migration "any name"
This command will create .cs file into migrations folder automatically, in which you can see your changes.
 
3) Last and final step is updating database with following command:
  • PM> Update-Database
That is how you can get benefit from database migrations in just 3 commands, this is very basic stuff you can have for you migrations, further advance skills will come from experience.Thanks