How to use Migrations to implement Code First for Entity framework and MVC

Code first is the way to write your code first and let the code take care of the Database and such for you. You shape your objects and you run custom tool to generate the Database for you.

Now, you should have the basic idea on how database tables , views and relationship works, but when you are using code first techniques you are flowing freely on your code and not have to be very concerned about the database.

 

Well, enough said, let’s just dive in..

 

There are 2 paths

1. If you are using NHibernate, you can use roundHouse for this (I will have a different post for that).

2. If you are using Entity Framework then you can use migrations tool supplied by Microsoft.(I am showing this here).

 

Here is how I do it.

 

I will have 2 objects, Person and address and the relationship will be very simple one to many. Keeping it simple for now.

Simply, an address can have multiple Person.

I am using MVC 3 with RAZOR.

 

 

 


So if you look at the above classes you can definitely tell that I just over simplified these.

Here is the important part. To use the Migration tool you need to do the following

  1. Create an constructor on your DbContext for EF to point to your Database. You will find the connectionstring name on your web.config field.for example
     
 

 

 

 

Open Package Manager Console

Activate the migration by typing in the following
 Enable-Migrations -“DataContext [DbName] (You find the dbName from your connectionstring).

 

 

3.

You will now have a Migration Folder with a Configuration.cs file that has your migration code.

Open that file and you will find the following constructor

 

public Configuration()         {             AutomaticMigrationsEnabled = false;         }

Change the AutomaticMigrationsEnabled to true for now.


4.

Configuration is where you control what happens and also can seed your data.

Once you have any changes, you can run the following command to update the database

Update-Database -Verbose

This will create the database for the first time.

 

From next time if you make any changes that require the whole database changes you have to pass in –Force key

Update-Database -Verbose -Force

 

This should get you started.

Leave a Reply

Your email address will not be published. Required fields are marked *