MVC Data Access Using Entity Framework and HTML Helpers

Look at the following procedure.

Step 1

Create a database with some sample data using the following SQL script.

  1. CREATE DATABASE MVC;  
  2.   
  3. USE MVC;  
  4.   
  5. CREATE TABLE dbo.Students(ID intName varchar(50), Gender varchar(6), Fees int);  
  6.   
  7. INSERT INTO dbo.Students  
  8. VALUES(1, 'Harry''Male', 2500);  
  9.   
  10. INSERT INTO dbo.Students  
  11. VALUES(2, 'Jane''Female', 2400);  
  12.   
  13. INSERT INTO dbo.Students  
  14. VALUES(3, 'Emma''Female', 2100);  
  15.   
  16. INSERT INTO dbo.Students  
  17. VALUES(4, 'Roster''Male', 2500);  
  18.   
  19. INSERT INTO dbo.Students  
  20. VALUES(5, 'Chris''Male', 2900);  
  21.   
  22. INSERT INTO dbo.Students  
  23. VALUES(6, 'Evan''Male', 2200);  
  24.   
  25. INSERT INTO dbo.Students  
  26. VALUES(7, 'Cathlie''Female', 2550);  
  27.   
  28. INSERT INTO dbo.Students  
  29. VALUES(8, 'Jack''Male', 2500);  
  30.   
  31. INSERT INTO dbo.Students  
  32. VALUES(9, 'Jone''Male', 2900);  
  33.   
  34. INSERT INTO dbo.Students  
  35. VALUES(10, 'Videra''Female', 2550);  
  36.   
  37. INSERT INTO dbo.Students  
  38. VALUES(11, 'Sara''Female', 2900);  
  39.   
  40. INSERT INTO dbo.Students  
  41. VALUES(12, 'Mak''Male', 2500);  
  42.   
  43. INSERT INTO dbo.Students  
  44. VALUES(13, 'Max''Male', 2550);  
  45.   
  46. INSERT INTO dbo.Students  
  47. VALUES(14, 'Brock''Male', 2900);  
  48.   
  49. INSERT INTO dbo.Students  
  50. VALUES(15, 'Eddie''Male', 2500);  
  51.   
  52. INSERT INTO dbo.Students  
  53. VALUES(16, 'Edna''Female', 2500);  
Step 2

Create a new MVC Project in Visual Studio and name it "MVCDataAccessByEntityFrame".

MVC Project

empty templet

Step 3

Install Entity Framework using Nuget package manager from Solution Explorer into your project.

nuget package manager

solution explorer

Step 4

Go to the Models folder in the Solution Explorer and add two class files.

Models

Step 5

Copy the following code to the preceding created class files.

Students.cs
  1. using System.ComponentModel.DataAnnotations.Schema;  
  2.   
  3. namespace MVCDataAccessByEntityFrame.Models  
  4. {  
  5.     [Table("Students")]  
  6.     public class Students  
  7.     {  
  8.         public int ID { getset; }  
  9.         public string Name { getset; }  
  10.         public string Gender { getset; }  
  11.         public int Fees { getset; }  
  12.     }  
  13. }  
StudentsContext.cs
  1. using System.Data.Entity;  
  2. namespace MVCDataAccessByEntityFrame.Models  
  3. {  
  4.     public class StudentsContext : DbContext  
  5.     {  
  6.         public DbSet<Students> Students { getset; }  
  7.     }  
  8. }  
Step 6

Go to the Controllers folder and add a controller to it.

Controllers

Step 7

Add the following code to the controller.
  1. using MVCDataAccessByEntityFrame.Models;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web.Mvc;  
  5.   
  6. namespace MVCDataAccessByEntityFrame.Controllers  
  7. {  
  8.     public class StudentsController : Controller  
  9.     {  
  10.         public ActionResult Index()  
  11.         {  
  12.             StudentsContext studentsContext = new StudentsContext();  
  13.             List<Students> students = studentsContext.Students.ToList();  
  14.             return View(students);  
  15.         }  
  16.         public ActionResult Details(int id)  
  17.         {  
  18.             StudentsContext studentsContext = new StudentsContext();  
  19.             Students students = studentsContext.Students.Single(stu => stu.ID == id);  
  20.             return View(students);  
  21.         }  
  22.   
  23.     }  
  24. }  
Step 8

Press Ctrl + Shift + B and then right-click on the index method and add a view.

index method

Step 9

Add the following code to the Index.cshtml.
  1. @model IEnumerable<MVCDataAccessByEntityFrame.Models.Students>  
  2. @using MVCDataAccessByEntityFrame.Models;  
  3. @{  
  4.     ViewBag.Title = "Students List";  
  5. }  
  6.   
  7. <h2>Students List</h2>  
  8. <ol start="1">  
  9.     @foreach (Students students in @Model)  
  10.     {  
  11.         <li id="item">  
  12.             @Html.ActionLink(students.Name, "Details"new { id = students.ID })  
  13.         </li>  
  14.     }  
  15. </ol>  
Step 10

Right-click on the Details method and add a view again.

add a view

Step 11

Add the following code to details.cshtml.
  1. @model MVCDataAccessByEntityFrame.Models.Students  
  2.   
  3. @{  
  4.     ViewBag.Title = "Students Details";  
  5. }  
  6.   
  7. <table border="1">  
  8.     <tr>  
  9.         <td><b>ID:</b></td>  
  10.         <td>  
  11.             @Model.ID  
  12.         </td>  
  13.     </tr>  
  14.     <tr>  
  15.         <td><b>Name:</b></td>  
  16.         <td>@Model.Name</td>  
  17.     </tr>  
  18.     <tr>  
  19.         <td><b>Gender:</b></td>  
  20.         <td>@Model.Gender</td>  
  21.     </tr>  
  22.     <tr>  
  23.         <td><b>Fees:</b></td>  
  24.         <td>@Model.Fees</td>  
  25.     </tr>  
  26. </table>  
  27. <br />  
  28. @Html.ActionLink("Back to Students List""Index")  
Step 12

Go to the web.config file in the Views folder in Solution Explorer and add the following code.
  1. <connectionStrings>  
  2.   <add name="StudentsContext" connectionString="server=ANKITBANSALPC; database = MVC; integrated security = SSPI" providerName="System.Data.SqlClient"/>  
  3. </connectionStrings>  
Step 13

Go to the Route.config file in the App_Start folder and paste in the following code.
  1. using System.Web.Mvc;  
  2. using System.Web.Routing;  
  3.   
  4. namespace MVCDataAccessByEntityFrame  
  5. {  
  6.     public class RouteConfig  
  7.     {  
  8.         public static void RegisterRoutes(RouteCollection routes)  
  9.         {  
  10.             routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
  11.   
  12.             routes.MapRoute(  
  13.                 name: "Default",  
  14.                 url: "{controller}/{action}/{id}",  
  15.                 defaults: new { controller = "Students", action = "Index", id = UrlParameter.Optional }  
  16.             );  
  17.         }  
  18.     }  
  19. }  
Step 14

Save all the changes and Press F5 to run the project and you will see a list of Students and on clicking a specific student name, you will see the details of that student.

student list

details

Explanation

Students.cs
  • Add some public properties that correspond to database columns.

  • Sometimes the table name in the database and the class file name are not same, so to explicitly declare the table name we use the Table attribute at the top because MVC by default thinks that the name of the class file is the name of the table of the database.

StudentsContext.cs

  • We first inherit the DBContext class that is a part of Entity Framework. This class doed all the database connectivity without having to write the ADO.NET code.

  • We are storing the data of the students table in the Dbset collection since it stores all the retrieved data from the table.

  • This file finds the Students class that we created earlier and matches all the properties defined there.

  • Hence the mapping of the table and the class properties is done.

StudentsController.cs

  • Now we create two methods, Index and Details. Index shows the list of data and Details shows the data of a specific student based on its ID that we pass as a parameter to the Details method.

  • For the index method, we create the instance of the StudentsContext class and use its property Students that contains the list of students and saved this data in an instance of List<Students> interface.

    Finally, we pass this instance to the view for rendering.

  • For the details method, we again created an instance of the StudentContext class and use its property Students that contains the list of students and using a LINQ query Single function, we fetch the data of the student by passing its id as a parameter. Since this returns a Students class, we created the instance of the Students class and pass its instance to the view for rendering.

Index.cshtml

  • At first, we make the namespace as IEnumerable since it can store a list of data.

  • We iterate through each student using the foreach loop and then added each student item to the <li> tag. This will populate the list of students for us.

Details.cshtml

  • We simply used the properties of model to populate the data in our table. Simple HTML is used. Web.config.

  • We add a connection string to connect to the database. Notice that the name of the connection string should be the same as that of the StudentsContext file since by default, MVC searches connection strings by the same name.

Route.config

  • Just change the name of controller to Students from Home so that when our page loads, it directly calls the Index action method.

Download Source code here.

See this article in my own blog: debugsolutions and technewsinform.


Similar Articles