Click here to Skip to main content
11,636,300 members (80,173 online)
Click here to Skip to main content

Complete CRUD Operations in MVC 4 using Entity Framework 5 Without Writing a Single Line of Code

, 26 Nov 2014 CPOL 175.6K 5.8K 141
Rate this:
Please Sign up or sign in to vote.
Complete CRUD Operations in MVC 4 using Entity Framework 5 without writing a single line of code.

Introduction

In this article, I’ll describe how to perform basic CRUD operations in an MVC4 application with the help of Entity Framework 5 without writing a single line of code. EF and MVC had advanced themselves to the level that we don’t have to put effort in doing extra work.

I) 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 a change in Model’s state.

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

II) 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 a simple language, 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 & storing the data in the database.

Hope this gives a glimpse of an ORM and EntityFramework.

III) MVC Application

Step 1: Create a database named LearningKO and add a table named student to it, script of the table is as follows:

USE [LearningKO]
GO
/****** Object:  Table [dbo].[Student]    Script Date: 12/04/2013 23:58:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Student](
	[StudentId] [nvarchar](10) NOT NULL,
	[FirstName] [nvarchar](50) NULL,
	[LastName] [nvarchar](50) NULL,
	[Age] [int] NULL,
	[Gender] [nvarchar](50) NULL,
	[Batch] [nvarchar](50) NULL,
	[Address] [nvarchar](50) NULL,
	[Class] [nvarchar](50) NULL,
	[School] [nvarchar](50) NULL,
	[Domicile] [nvarchar](50) NULL,
 CONSTRAINT [PK_Student] PRIMARY KEY CLUSTERED 
(
	[StudentId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, _
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
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')
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')
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')
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' Noida', N'12th', N'LFS', N'Delhi')

Step 2: Open your Visual Studio (Visual Studio Version should be greater than or equal to 12) and add an MVC Internet application.

I have given it a name “KnockoutWithMVC4”.

Step 3: You’ll get a full structured MVC application with default Home controller in the Controller folder. By default, entity framework is downloaded as a package inside application folder but if not, you can add entity framework package by right clicking the project, select manage nugget packages and search and install Entity Framework.

Step 4: Right click project file, select add new item and add ADO.NET entity data model, follow the steps in the wizard as shown below:

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

Select tables to be added to the model. In our case, it’s Student Table.

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

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

Step 6: We see our student controller prepared with all the CRUD operation actions as shown below:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
	
namespace KnockoutWithMVC4.Controllers
{
    public class StudentController : Controller
    {
        private LearningKOEntities db = new LearningKOEntities();
	
        //
        // GET: /Student/
	
        public ActionResult Index()
        {
            return View(db.Students.ToList());
        }
	
        //
        // GET: /Student/Details/5
	
        public ActionResult Details(string id = null)
        {
            Student student = db.Students.Find(id);
            if (student == null)
            {
                return HttpNotFound();
            }
            return View(student);
        }
	
        //
        // GET: /Student/Create

        public ActionResult Create()
        {
            return View();
        }
	
        //
        // POST: /Student/Create

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(Student student)
        {
            if (ModelState.IsValid)
            {
                db.Students.Add(student);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
	
            return View(student);
        }
	
        //
        // GET: /Student/Edit/5
	
        public ActionResult Edit(string id = null)
        {
            Student student = db.Students.Find(id);
            if (student == null)
            {
                return HttpNotFound();
            }
            return View(student);
        }
	
        //
        // POST: /Student/Edit/5
	
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(Student student)
        {
            if (ModelState.IsValid)
            {
                db.Entry(student).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(student);
        }
	
        //
        // GET: /Student/Delete/5

        public ActionResult Delete(string id = null)
        {
            Student student = db.Students.Find(id);
            if (student == null)
            {
	                return HttpNotFound();
            }
            return View(student);
        }
	
        //
        // POST: /Student/Delete/5
	
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(string id)
        {
            Student student = db.Students.Find(id);
            db.Students.Remove(student);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
	
        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}

Step 7: Open App_Start folder and, change the name of controller from Home to Student.

The code will become as:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Student", 
        action = "Index", id = UrlParameter.Optional }
    );
}

Step 8: Now press F5 to run the application, and you’ll see the list of all students we added into table Student while creating it is displayed. Since the CRUD operations are automatically written, we have action results for display list and other Edit, Delete and Create operations. Note that views for all the operations are created in Views Folder under Student Folder name.

Now you can perform all the operations on this list.

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

Now create new student.

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

In database:

Similarly for Edit:

Change any field and press save. The change will be reflected in the list and database:

For Delete:

Student deleted.

And in database:

Not a single line of code is written till now.

Conclusion

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

Note: Few of the images in this article are taken via Google search.

You can follow my articles at csharppulse.blogspot.in.

Happy coding!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Akhil Mittal
Technical Lead
India India
I am a C# Corner MVP,a Code project MVP,blogger,programmer by heart and currently working as a Sr. Analyst in Magic Software and have an experience of more than 8 years in C#.Net. I am a B.Tech in Computer Science and hold a diploma in Information Security and Application Development. My work experience includes Development of Enterprise Applications using C#,.Net and Sql Server,Analysis as well as Research and Development. I am a MCP in Web Applications(MCTS-70-528,MCTS-70-515) and .Net Framework 2.0 (MCTS-70-536). Visit my personal blog A Practical Approach for more informative articles.
____________________________________________________________________________________________________

Article of the Day on Microsoft's site http://www.asp.net/community/articles on 16 Aug 2013.
Article of the Day on Microsoft's site http://www.asp.net/community/articles on 28 Aug 2013.
Article of the Day on Microsoft's site http://www.asp.net/community/articles on 08 Sept 2013.
Article of the Day on Microsoft's site http://www.asp.net/community/articles on 29 Sept 2013.
Article of the Day on Microsoft's site http://www.asp.net/community/articles on 29 Oct 2013.
Article of the Day on Microsoft's site http://www.asp.net/community/articles on 21 May 2014.
Article of the Day on Microsoft's site http://www.asp.net/community/articles on 19 July 2014.
Article of the Day on Microsoft's site http://www.asp.net/community/articles on 01 June 2015.
Article of the Day on Microsoft's site http://www.asp.net/community/articles on 02 June 2015.
Article of the Day on Microsoft's site http://www.asp.net/community/articles on 08 June 2015.
Article of the Day on Microsoft's site http://www.asp.net/community/articles on 28 June 2015.
Article of the Day on Microsoft's site http://www.asp.net/community/articles on 28 July 2015.
Member of the month for July 2013 on C# Corner
May 2014 Month
Group type: Collaborative Group

267 members


You may also be interested in...

Comments and Discussions

 
SuggestionError creating new and solution Pin
VagnerKiesse15-Jun-15 5:28
professionalVagnerKiesse15-Jun-15 5:28 
GeneralRESTful API Pin
Akhil Mittal 18-May-15 18:57
mvp Akhil Mittal 18-May-15 18:57 
QuestionReally nice article Pin
Member 1002407712-May-15 20:49
professionalMember 1002407712-May-15 20:49 
AnswerRe: Really nice article Pin
Akhil Mittal 12-May-15 23:22
mvp Akhil Mittal 12-May-15 23:22 
GeneralAWESOME Pin
marcelinha14-Apr-15 10:29
professionalmarcelinha14-Apr-15 10:29 
GeneralRe: AWESOME Pin
Akhil Mittal 29-Apr-15 1:57
mvp Akhil Mittal 29-Apr-15 1:57 
GeneralRe: AWESOME Pin
Akhil Mittal 18-May-15 18:56
mvp Akhil Mittal 18-May-15 18:56 
Questiondatanotation issue in .edmx Pin
saineshwar25-Dec-14 2:30
membersaineshwar25-Dec-14 2:30 
GeneralQUery Pin
Member 10745682-Dec-14 17:05
memberMember 10745682-Dec-14 17:05 
QuestionProblem with Create Pin
Vikash Ranjan Jha24-Nov-14 22:58
professionalVikash Ranjan Jha24-Nov-14 22:58 
AnswerRe: Problem with Create Pin
Akhil Mittal 25-Nov-14 18:50
mvp Akhil Mittal 25-Nov-14 18:50 
QuestionGood Example Pin
Member 111137406-Nov-14 18:28
memberMember 111137406-Nov-14 18:28 
AnswerRe: Good Example Pin
Akhil Mittal 7-Nov-14 1:27
mvp Akhil Mittal 7-Nov-14 1:27 
QuestionHaving a Error While Creating a Data Pin
Maria Norbert10-Oct-14 2:38
memberMaria Norbert10-Oct-14 2:38 
AnswerRe: Having a Error While Creating a Data Pin
Member 1002407712-May-15 20:54
professionalMember 1002407712-May-15 20:54 
QuestionUnable to add StudentController. Pin
Member 107435337-Oct-14 2:38
memberMember 107435337-Oct-14 2:38 
AnswerRe: Unable to add StudentController. Pin
sonnguyen36027-Oct-14 6:09
membersonnguyen36027-Oct-14 6:09 
QuestionThis is my video, people can reference to understand about CRUD in ASP MVC 4 Pin
Member 111313585-Oct-14 17:13
memberMember 111313585-Oct-14 17:13 
GeneralMy vote of 5 Pin
csharpbd27-Aug-14 9:13
membercsharpbd27-Aug-14 9:13 
AnswerRe: My vote of 5 Pin
Akhil Mittal 27-Aug-14 20:35
mvp Akhil Mittal 27-Aug-14 20:35 
QuestionStep 7: No App_Start folder in Visual Studio 2010? Pin
josebrwn30-Jul-14 12:48
memberjosebrwn30-Jul-14 12:48 
AnswerRe: Step 7: No App_Start folder in Visual Studio 2010? Pin
Akhil Mittal 30-Jul-14 17:39
mvp Akhil Mittal 30-Jul-14 17:39 
GeneralMy vote of 1 Pin
Kamran571-Jul-14 3:14
memberKamran571-Jul-14 3:14 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun26-Jun-14 0:08
memberHumayun Kabir Mamun26-Jun-14 0:08 
GeneralRe: My vote of 5 Pin
Akhil Mittal1-Jul-14 19:29
mvpAkhil Mittal1-Jul-14 19:29 
QuestionFacing problem while trying to create new student Pin
Saadmaan Mahmid20-Apr-14 19:36
memberSaadmaan Mahmid20-Apr-14 19:36 
AnswerRe: Facing problem while trying to create new student Pin
Akhil_Mittal9-May-14 7:21
mvpAkhil_Mittal9-May-14 7:21 
GeneralRe: Facing problem while trying to create new student Pin
Akhil_Mittal9-May-14 7:21
mvpAkhil_Mittal9-May-14 7:21 
GeneralRe: Facing problem while trying to create new student Pin
Saadmaan Mahmid21-May-14 2:36
memberSaadmaan Mahmid21-May-14 2:36 
GeneralRe: Facing problem while trying to create new student Pin
Marvin Haagsma8-Jan-15 6:53
memberMarvin Haagsma8-Jan-15 6:53 
Generalnice Pin
Hamsini Reddy24-Mar-14 22:41
memberHamsini Reddy24-Mar-14 22:41 
GeneralRe: nice Pin
Akhil_Mittal12-Apr-14 0:38
mvpAkhil_Mittal12-Apr-14 0:38 
QuestionAbout the Migration Pin
Pathak Trilok Manubhai26-Feb-14 1:26
memberPathak Trilok Manubhai26-Feb-14 1:26 
QuestionGetting Cascading error while deleting. Pin
Member 1053820818-Feb-14 23:55
memberMember 1053820818-Feb-14 23:55 
GeneralMy vote of 5 Pin
m_aks19-Dec-13 21:59
memberm_aks19-Dec-13 21:59 
GeneralRe: My vote of 5 Pin
Akhil_Mittal19-Dec-13 22:00
groupAkhil_Mittal19-Dec-13 22:00 
QuestionThank you Pin
Siya Khumalo18-Dec-13 20:48
groupSiya Khumalo18-Dec-13 20:48 
AnswerRe: Thank you Pin
Akhil_Mittal18-Dec-13 22:29
groupAkhil_Mittal18-Dec-13 22:29 
GeneralMy vote of 5 Pin
manoj kumar choubey17-Dec-13 18:38
membermanoj kumar choubey17-Dec-13 18:38 
GeneralRe: My vote of 5 Pin
Akhil_Mittal18-Dec-13 16:50
groupAkhil_Mittal18-Dec-13 16:50 
QuestionDonwload link is not working Pin
nullpointer17-Dec-13 15:46
membernullpointer17-Dec-13 15:46 
AnswerRe: Donwload link is not working Pin
Akhil_Mittal17-Dec-13 16:57
groupAkhil_Mittal17-Dec-13 16:57 
Hi,

Its fixed now.Please check.
Thanks
Do not forget to comment and rate the article if it helped you by any means Smile | :) ...
For any technical requirement related to .net ,OOPS,C# and design patterns contact me on akhil.mittal20@gmail.com

GeneralRe: Donwload link is not working Pin
nullpointer18-Dec-13 17:49
membernullpointer18-Dec-13 17:49 
GeneralRe: Donwload link is not working Pin
Akhil_Mittal18-Dec-13 22:30
groupAkhil_Mittal18-Dec-13 22:30 
GeneralRe: Donwload link is not working Pin
nullpointer19-Dec-13 18:08
membernullpointer19-Dec-13 18:08 
GeneralRe: Donwload link is not working Pin
Akhil_Mittal19-Dec-13 18:12
groupAkhil_Mittal19-Dec-13 18:12 
QuestionNice Article - One Technical Issue Pin
MichaelCullina16-Dec-13 15:23
memberMichaelCullina16-Dec-13 15:23 
AnswerRe: Nice Article - One Technical Issue Pin
Akhil_Mittal16-Dec-13 17:02
groupAkhil_Mittal16-Dec-13 17:02 
Generalgood ...keep it up Pin
Bhushan Gupta15-Dec-13 8:41
memberBhushan Gupta15-Dec-13 8:41 
GeneralRe: good ...keep it up Pin
Akhil_Mittal3-Jan-14 21:38
mvpAkhil_Mittal3-Jan-14 21:38 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150728.1 | Last Updated 27 Nov 2014
Article Copyright 2013 by Akhil Mittal
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid