Practical Approach to Learn MVC: Part 3

This article explains MVC in ASP.Net. I will only show the practical (programmatic) approach of learning ASP.Net MVC.

Introduction
 
In this article, I am not paying much attention to the theory.
 
This is the continuation of Part 2. If you are new to MVC then I will strongly recommend you to please go through parts one and two before proceeding to this article. Click the following links for the previous parts of this tutorial.
In the last tutorial, we saw the basics of Views. We will now discuss the concept of the Model in MVC. A MVC Model is typically a class (of C# or VB.NET). All the views and the controller can access the Model class. The main purpose of the Model class is to communicate to the database and apply validation on that data.
 
Data access in MVC using Entity Framework
 
By using the Entity Framework we can communicate with the database in MVC. There are the following three approaches to communicate with a database in Entity Framework.
  1. Code First Approach
  2. Database First
  3. Model First
Code First Approach
 
As the name suggests, in this approach, we will write the code first to generate the database and in one good day, we will run that code to see the database in the DB server. Here are a few possible scenarios where we can implement the Code First Approach.
  • If you are a hard-core developer and always like to play with code then the Code First Approach is fit for you.

  • If you want full control over your database design without much knowledge of SQL and a DBA.

  • If the application is brand new and is there is no existing database for that application.
In the following example, we will go with an Employee and a department table. There is the following procedure you need to follow for the Code First Approach of Entity Framework and then migrate it to a SQL Server database.
 
Step 1
 
Open Visual Studio and go to New project under the web tab.
 
web application 
 
Step 2
 
Select MVC from the template and click OK.
 
MVC 
 
Step 3
 
The MVC application solution has been automatically created with some default controller Models and Views. You can delete it or leave as it is.
 
Then right-click on the Models folder and select Add and select the class then name it Employee.
 
add class 
 
Now your class is ready with the following code.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5.   
  6. namespace CodeFirstApproachWithEmployeesInfo.Models  
  7. {  
  8.     public class Employee  
  9.     {  
  10.   
  11.     }  
  12. } 
Add some properties in Employee class
  1. public class Employee    
  2. {    
  3.     public int Id { getset; }    
  4.     public string EmpName { getset; }    
  5.     public int Salary { getset; }    
  6.     public DateTime  EmpDOB { getset; }  
  7. } 
This Employee class will represent the Employee table in the database.
 
Step 4
 
After adding the Employee Model class add the EmployeeDBContext class in the same Employee class file. Later the EmployeeDBContext will represent the connection string name of the web.config file. This class name and connection string name must be the same. Inherit the EmployeeDBContext class from DbContext. For this you need to add the namespace using System.Data.Entity.
  1. public class EmployeeDBContext : DbContext  
  2. {  
  3.    public DbSet<Employee> Employees { getset; }  
  4. }  
Now add a property Employees of DbSet<Employee>.
 
Note: The class named EmployeeDBContext class corresponds to the Entity Framework employee's database context. That is helpful for retrieving, storing and updating the employee class instances in the database. The DbContext class provided by the Entity Framework is the base class of EmployeeDBContext.
 
Step 5
 
Add the following connection string inside the web.config file.
  1. <add name="EmployeeDBContext" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFileName=|DataDirectory|\EmployeesDB.mdf;Integrated Security=True" providerName ="System.Data.SqlClient" />  
Replace the database file name with yours.
 
Our connections string is now ready. We will now do CRUD operations with the Employee table.
 
Step 6
 
Build the project. Then right-click on the Controllers folder. Select add New Scadffolded Item. 
 
New Scadffolded Item
 
Step 7
 
Select the MVC tab and select MVC 5 Controller with Views, using Entity Framework and click on Add.
 
select MVC 5 Controller with Views
 
Step 8
 
Select the Model class as Employee and context class as EmployeeDBContext and click on Add.

EmployeeDBContext
 
Step 9
 
Now the EmployeesController and CRUD operations view is ready with all the required code. In the following image you can see the views and controller. Open the controller class and take a close look at it.
 
controller 
 
There will be a method.
  1. // GET: Employees  
  2. public ActionResult Index()  
  3. {  
  4.    return View(db.Employees.ToList());  
  5. }  
When we run the Index view the first time a database will be created automatically and we will get the following screen.

index
Click on Create New to add the employee.
 
add the employee 
 
When you click the Create button it will automatically redirect to the index view where the employees list will show as in the following:
 
create new index 
 
Now you can click Edit to edit the record, delete to delete the record and so on.
 
The EmployeeDB is in the SQL Server Express LocalDB since we have specified the SQL Server Express path in our database. So first we migrate this database to a SQL Server database then we will customize the pre-defend template.
 
SQL Server LocalDB is the data source used by default by Visual Studio. When you work with the Entity Framework Code First Approach, it automatically creates a database, if the database did not exist. You can view it from the "App_Data" folder in the Solution Explorer as we are seeing it in the following image.
 
app data 
 
Migration in Entity Framework Code First
 
We need to use the following procedure to migrate the database.
 
Step A
 
First delete the database in App_Data and build the project. Then use the procedure shown in the following image.
 
NuGet package manager 
 
Step B
 
Type in the following command in the Package Manager Console.
 
Enable-Migrations -ContextTypeName CodeFirstApproachWithEmployeesInfo.Models.EmployeeDBContext
 
And press Enter. You will get the following message as shown in the image.
 
package manager console 
 
It creates a "Configurations.cs" file in the new folder (named Migrations folder) in your Solution Explorer. 
  1. namespace CodeFirstApproachWithEmployeesInfo.Migrations  
  2. {  
  3.     using System;  
  4.     using System.Data.Entity;  
  5.     using System.Data.Entity.Migrations;  
  6.     using System.Linq;  
  7.   
  8.     internal sealed class Configuration : DbMigrationsConfiguration<CodeFirstApproachWithEmployeesInfo.Models.EmployeeDBContext>  
  9.     {  
  10.         public Configuration()  
  11.         {  
  12.             AutomaticMigrationsEnabled = false;  
  13.         }  
  14.   
  15.         protected override void Seed(CodeFirstApproachWithEmployeesInfo.Models.EmployeeDBContext context)  
  16.         {  
  17.             //  This method will be called after migrating to the latest version.  
  18.   
  19.             //  You can use the DbSet<T>.AddOrUpdate() helper extension method   
  20.             //  to avoid creating duplicate seed data. E.g.  
  21.             //  
  22.             //    context.People.AddOrUpdate(  
  23.             //      p => p.FullName,  
  24.             //      new Person { FullName = "Andrew Peters" },  
  25.             //      new Person { FullName = "Brice Lambson" },  
  26.             //      new Person { FullName = "Rowan Miller" }  
  27.             //    );  
  28.             //  
  29.         }  
  30.     }  
  31. }  
Step C
 
The DmployeeDb database has been deleted. Open the Configuration.as and insert a seed value for the employee table using the following code.
  1. protected override void Seed(CodeFirstApproachWithEmployeesInfo.Models.EmployeeDBContext context)  
  2. {  
  3.     //  This method will be called after migrating to the latest version.  
  4.   
  5.     //  You can use the DbSet<T>.AddOrUpdate() helper extension method   
  6.     //  to avoid creating duplicate seed data. E.g.  
  7.     //  
  8.     context.Employees.AddOrUpdate(i=>i.EmpName,              
  9.       new Employee   
  10.       {  
  11.           EmpName = "Manish Kumar",   
  12.           Salary= 30000,  
  13.           EmpDOB = Convert .ToDateTime ("07/12/1990")   
  14.       },  
  15.        new Employee   
  16.       {  
  17.           EmpName = "Namit Kumar",   
  18.           Salary= 20000,  
  19.           EmpDOB = Convert .ToDateTime ("07/11/1988")   
  20.       },  
  21.        new Employee   
  22.       {  
  23.           EmpName = "Vekat Kumar",   
  24.           Salary= 25000,  
  25.           EmpDOB = Convert .ToDateTime ("07/01/1980")   
  26.       }  
  27.     );  
  28.     //  
  29. }  
We need to add a Models folder reference here to use the Employee class. The Migration class you created helps to create a database. This is the reason for deleting your database mdf file.
 
Step D
 
Now build the project and in the Package Manager Console enter the following command.
 
add-migration Initial
 
You will get the following message after the success of the command.
 
migration Initial 
 
The add-migration Initial command creates a new class file in your Migration folder. The new class named "(DataStamp)_initial.cs code" helps to create a schema for the database. This file's code implements the Employee table in your Employees database.
  1. public override void Up()  
  2. {  
  3.        CreateTable(  
  4.        "dbo.Employees",  
  5.        c => new  
  6.        {  
  7.              Id = c.Int(nullable: false, identity: true),  
  8.              EmpName = c.String(),  
  9.              Salary = c.Int(nullable: false),  
  10.              EmpDOB = c.DateTime(nullable: false),  
  11.        })  
  12.       .PrimaryKey(t => t.Id);  
  13.               
  14. }  
  15.           
  16. public override void Down()  
  17. {  
  18.       DropTable("dbo.Employees");  
  19. }  
Step E

Enter the following command in your Package Manager Console:

update-database

You will get the following message after the success of the command.

update database

If this results in an error then just check whether or not the local DB was deleted. If not deleted then do the process again.

Then, Migration down Run the program project and see the result.

In the next tutorial, we will learn how to edit the table add a new table and apply all the changes to the database and also we will customize the default view generated by the Visual Studio 2013.

Summary

In this illustration, you came to understand the basics of the MVC Model and how to communicate with a database using the Entity Framework Code First Approach.

Thanks.

I would like to get feedback from my readers. Please post your feedback, question, or comments about this article.