Complete CRUD Operations in MVC 4 Using Entity Framework 5 Without Writing Code

Introduction

This article describes how to perform basic CRUD operations in an MVC4 application using Entity Framework 5 without writing a single line of code. Entity Framework and MVC have advanced to the level that we don't need to put effort into doing extra work.

  1. MVC

    • Model: The business entity on which the overall application operates. Many applications use a persistent storage mechanism (such as a database) to store data. MVC does not specifically mention the data access layer because it is understood to be encapsulated by the Model.
       
    • View: The user interface that renders the model into a form of interaction.
       
    • Controller: Handles a request from a view and updates the model that results in a change in the Model's state.

    To implement MVC in .NET we need mainly three classes (View, Controller and the Model).
     
  2. Entity Framework

    Let's have a look at the standard definition of Entity Framework given by Microsoft:

    "The Microsoft ADO.NET Entity Framework is an Object/Relational Mapping (ORM) framework that enables developers to work with relational data as domain-specific objects, eliminating the need for most of the data access plumbing code that developers usually need to write. Using the Entity Framework, developers issue queries using LINQ, then retrieve and manipulate data as strongly typed objects. The Entity Framework's ORM implementation provides services like change tracking, identity resolution, lazy loading, and query translation so that developers can focus on their application-specific business logic rather than the data access fundamentals."

    In simple terms, Entity Framework is an Object/Relational Mapping (ORM) framework. It is an enhancement to ADO.NET, an upper layer to ADO.Net that gives developers an automated mechanism for accessing and storing the data in the database.

    Hope this provides a glimpse at an ORM and EntityFramework.
     
  3. MVC Application

    Step 1: Create a database named "LearningKO" and add a table named "student" to it, the script of the table is as follows:
    1. USE [LearningKO]  
    2. GO  
    3. /****** Object:  Table [dbo].[Student]    Script Date: 12/04/2013 23:58:12 ******/  
    4. SETANSI_NULLS ON  
    5. GO  
    6. SETQUOTED_IDENTIFIER ON  
    7. GO  
    8. CREATETABLE [dbo].[Student](  
    9.       [StudentId] [nvarchar](10)NOT NULL,  
    10.       [FirstName] [nvarchar](50)NULL,  
    11.       [LastName] [nvarchar](50)NULL,  
    12.       [Age] [int]NULL,  
    13.       [Gender] [nvarchar](50)NULL,  
    14.       [Batch] [nvarchar](50)NULL,  
    15.       [Address] [nvarchar](50)NULL,  
    16.       [Class] [nvarchar](50)NULL,  
    17.       [School] [nvarchar](50)NULL,  
    18.       [Domicile] [nvarchar](50)NULL,  
    19. CONSTRAINT [PK_Student] PRIMARYKEY CLUSTERED  
    20. (  
    21.       [StudentId]ASC  
    22. )WITH(PAD_INDEX = OFF,STATISTICS_NORECOMPUTE = OFF,IGNORE_DUP_KEY =OFF,ALLOW_ROW_LOCKS  =ON,ALLOW_PAGE_LOCKS  =ON)ON [PRIMARY]  
    23. )ON [PRIMARY]  
    24. GO  
    25. INSERT [dbo].[Student]([StudentId], [FirstName], [LastName], [Age], [Gender], [Batch], [Address], [Class], [School], [Domicile]) VALUES(N'1',N'Akhil',N'Mittal', 28,N'Male',N'2006',N'Noida',N'Tenth',N'LFS',N'Delhi')  
    26. INSERT [dbo].[Student]([StudentId], [FirstName], [LastName], [Age], [Gender], [Batch], [Address], [Class], [School], [Domicile]) VALUES(N'2',N'Parveen',N'Arora', 25,N'Male',N'2007',N'Noida',N'8th',N'DPS',N'Delhi')  
    27. INSERT [dbo].[Student]([StudentId], [FirstName], [LastName], [Age], [Gender], [Batch], [Address], [Class], [School], [Domicile]) VALUES(N'3',N'Neeraj',N'Kumar', 38,N'Male',N'2011',N'Noida',N'10th',N'MIT',N'Outside Delhi')  
    28. INSERT [dbo].[Student]([StudentId], [FirstName], [LastName], [Age], [Gender], [Batch], [Address], [Class], [School], [Domicile]) VALUES(N'4',N'Ekta',N'Mittal', 25,N'Female',N'2005',N'  
    29. Noida',N'12th',N'LFS',N'Delhi')  

    Create Database

    Step 2:
    Open your Visual Studio (the Visual Studio Version should be greater than or equal to 12) and add an MVC internet application as in the following:

    Open your Visual Studio

    MVC internet application

    I have given it the name "KnockoutWithMVC4".

    Step 3: You'll get a fully structured MVC application with default Home controller in the Controller folder. By default Entity Framework is downloaded as a package in the application folder, but if not then you can add the Entity Framework package by right-clicking the project, select "Manage nugget packages" and search and install the Entity Framework.

    nugget packages

    Entity Framework package

    Step 4: Right-click the project file, select "Add a new item" and add the ADO .Net Entity Data Model, follow the procedure in the wizard as shown below:

    Add a new item

    ADO .Net Entity Data Model

    Generate a model from the database

    Generate a model from the database, select your server and "LearningKO" database name, the connection string will automatically be added to your Web.Config, name that connection string "LearningKOEntities".

    tables to be added to the model

    Select tables to be added to the model. In our case it's the "Student" table.

    tables added to the model

    Step 5: Now add a new controller to the Controller folder, right-click the controller folder and add a controller named "Student". Since we have already created our data model, we can choose for an option where CRUD actions are created by the chosen Entity Framework data model.

    add a new controller

    add a controller name

    • Name your controller as "StudentController",
    • From the Scaffolding Options, select "MVC controller with read/write actions and views, using Entity Framework".
    • Select the Model class as "Student" that lies in our solution.
    • Select the Data Context class as "LearningKOEntities" that is added to our solution when we added the Entity Framework data model.
    • Select Razor as the rendering engine for views.
    • Click "Advanced options", select "Layout or master page" and select "_Layout.cshtml" from the shared folder.

    Layout or master page

    Step 6:
    We see out student controller prepared with all the CRUD operation actions as shown below:
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Data;  
    4. using System.Data.Entity;  
    5. using System.Linq;  
    6. using System.Web;  
    7. using System.Web.Mvc;   
    8. namespace KnockoutWithMVC4.Controllers  
    9. {  
    10.     publicclassStudentController : Controller  
    11.     {  
    12.         private LearningKOEntities db = new LearningKOEntities();   
    13.         //  
    14.         // GET: /Student/  
    15.         public ActionResult Index()  
    16.         {  
    17.             return View(db.Students.ToList());  
    18.         }   
    19.         //  
    20.         // GET: /Student/Details/5  
    21.         public ActionResult Details(string id = null)  
    22.         {  
    23.             Student student = db.Students.Find(id);  
    24.             if (student == null)  
    25.             {  
    26.                 return HttpNotFound();  
    27.             }  
    28.             return View(student);  
    29.         }   
    30.         //  
    31.         // GET: /Student/Create   
    32.         public ActionResult Create()  
    33.         {  
    34.             return View();  
    35.         }   
    36.         //  
    37.         // POST: /Student/Create   
    38.         [HttpPost]  
    39.         [ValidateAntiForgeryToken]  
    40.         public ActionResult Create(Student student)  
    41.         {  
    42.             if (ModelState.IsValid)  
    43.             {  
    44.                 db.Students.Add(student);  
    45.                 db.SaveChanges();  
    46.                 return RedirectToAction("Index");  
    47.             }   
    48.             return View(student);  
    49.         }  
    50.         //  
    51.         // GET: /Student/Edit/5  
    52.         public ActionResult Edit(string id = null)  
    53.         {  
    54.             Student student = db.Students.Find(id);  
    55.             if (student == null)  
    56.             {  
    57.                 return HttpNotFound();  
    58.             }  
    59.             return View(student);  
    60.         }   
    61.         //  
    62.         // POST: /Student/Edit/5   
    63.         [HttpPost]  
    64.         [ValidateAntiForgeryToken]  
    65.         public ActionResult Edit(Student student)  
    66.         {  
    67.             if (ModelState.IsValid)  
    68.             {  
    69.                 db.Entry(student).State = EntityState.Modified;  
    70.                 db.SaveChanges();  
    71.                 return RedirectToAction("Index");  
    72.             }  
    73.             return View(student);  
    74.         }   
    75.         //  
    76.         // GET: /Student/Delete/5   
    77.         public ActionResult Delete(string id = null)  
    78.         {  
    79.             Student student = db.Students.Find(id);  
    80.             if (student == null)  
    81.             {  
    82.                 return HttpNotFound();  
    83.             }  
    84.             return View(student);  
    85.         }   
    86.         //  
    87.         // POST: /Student/Delete/5   
    88.         [HttpPost, ActionName("Delete")]  
    89.         [ValidateAntiForgeryToken]  
    90.         public ActionResult DeleteConfirmed(string id)  
    91.         {  
    92.             Student student = db.Students.Find(id);  
    93.             db.Students.Remove(student);  
    94.             db.SaveChanges();  
    95.             return RedirectToAction("Index");  
    96.         }   
    97.         protectedoverridevoid Dispose(bool disposing)  
    98.         {  
    99.             db.Dispose();  
    100.             base.Dispose(disposing);  
    101.         }  
    102.     }  
    103. }  
    Step 7: Open the "App_Start" folder and change the name of the controller from "Home" to "Student".

    change the name of the controller

    The code will become:
    1. publicstaticvoid RegisterRoutes(RouteCollection routes)  
    2. {  
    3.     routes.IgnoreRoute("{resource}.axd/{*pathInfo}");   
    4.     routes.MapRoute(  
    5.     name: "Default",  
    6.     url: "{controller}/{action}/{id}",  
    7.     defaults: new { controller = "Student", action = "Index", id = UrlParameter.Optional });  
    8. }  
    Step 8: Now press F5 to run the application, and you'll see the list of all students we added into the Student table while creating it as displayed. Since the CRUD operations are automatically written, we have action results for a display list and other edit, delete and create operations. Note that views for all the operations are created in the "Views" folder under the "Student" folder name.

run the application

Now you can perform all the operations on this list.

perform all the operations on this list

MVC Code

Since I have not provided any validation checks on the model or created an existing student id, the code may break, so I am calling Edit Action in the create when we find that the id already exists.

MVC Edit Action

Now create a new student.

create a new student

We see that the student is created successfully and added to the list.

student created successfully

In the database:

database

Similarly for an edit:

edit the data

Change any field and press "Save".The change will be reflected in the list and the database.

change in the list and the database

For delete:

delete the data

Student deleted.

Student deleted

And in the database:

database Data After delete

Not a single line of code has been written.

Code written

Conclusion

In this tutorial we learned to set up an environment for MVC and Entity Framework 5 and perform CRUD operations on a Student model without writing a single line of code. You can expand the application by adding multiple Controllers, Models and Views.

Note: a few of the images in this article were obtained via Google search.

Read more:

Other Series

My other series of articles:

For more informative articles visit my Blog.



Happy Coding.

Next Recommended Readings