Using POCO Classes to create the database using MVC 4 Framework

Using POCO Classes to create the database using MVC 4 Framework

POCO means plain old class model , This is known as a code first approach for the Entity Framework. Here I am going to explain how to create the database and the tables using the MVC model classes .
So, let’s start , first of all we need to create a MVC4 project for it.
Click on the new project in Visual studio 2012
Now put a name for your MVC4 project  and click on the will show the MVC 4 project template dialog .
Select Internet application and click on the OK. The Internet application provides all the default setting for MVC4 project . It will create an internet application project for your MVC4 application.
Now right click on the model and add a new class which you want as a table into the database . Here I am creating a class named Country.
Now time to write some code.
I have added two property name CountryId and CountryName which will be columns for the My Country Table. Now Next question in your mind is what will be Table Name . So, by default entity framework creates table with the plural form of your class name. but if you want to specify the table name for your model then you can use the Table attribute as below.
Next step how to specify the primary key. For it you can use the key attribute and for specifying Identity columns you need to set DataGeneration.Identity as below.
 Here we have done with a basic model class for a basic Table . Next we need create a database context class. Add a new class under model as below.
Add the Entity namespace reference and inherit that context class from the DBContext Class as below.
Add the DBSet for your class  as below.
Now we need to specify the connection string in web config which will be used by this class. One thing you need to remember that by default EF assumes that your context class name is the connection string name until you specify it.
So this connection string will be used by EF to create new database named mytestDB under app_data .
Now we need to set the database initializer in Application_Start in global file as below.
We are done with all the configuration . Now the EF don’t have any idea about the model classes until we gives it first call. For it we will create a controller and the view but first compile your application once.
Right click on the controller folder and  go to add–> controller . It will show a dialog. select the controller name template  and the data context as below and click on the add button.
It will automatically generate the controller and the views . Now final step run the application and send the first hit to the EF by browsing the Country view.
And we are done. Check the App_Data folder by selecting view all files from the menu.
The EF created the database and the table . WELL DONE