SlideShare a Scribd company logo
Complete CRUD Operations in MVC 4 using Entity Framework 5 without writing single 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 on 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:
1. Step1: Create a data base 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')
2. Step2: Open your Visual Studio (Visual Studio Version should be greater than or equal to 12) and add
an MVC Internet application,
Mvc4 crud operations.-kemuning senja
I have given it a name “KnockoutWithMVC4”.
3. Step3: 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 click the project, select manage nugget packages and
search and install Entity Framework,
Mvc4 crud operations.-kemuning senja
4. 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,
Mvc4 crud operations.-kemuning senja
Generate model from data base, select your server and LearningKO data base 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.
5. Step5: 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 outr 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.
6. Step6: We see out student controller prepared with all the CRUD operation actions as shown below,
7. using System;
8. using System.Collections.Generic;
9. using System.Data;
10. using System.Data.Entity;
11. using System.Linq;
12. using System.Web;
13. using System.Web.Mvc;
14.
15. namespace KnockoutWithMVC4.Controllers
16. {
17. public class StudentController : Controller
18. {
19. private LearningKOEntities db = new LearningKOEntities();
20.
21. //
22. // GET: /Student/
23.
24. public ActionResult Index()
25. {
26. return View(db.Students.ToList());
27. }
28.
29. //
30. // GET: /Student/Details/5
31.
32. public ActionResult Details(string id = null)
33. {
34. Student student = db.Students.Find(id);
35. if (student == null)
36. {
37. return HttpNotFound();
38. }
39. return View(student);
40. }
41.
42. //
43. // GET: /Student/Create
44.
45. public ActionResult Create()
46. {
47. return View();
48. }
49.
50. //
51. // POST: /Student/Create
52.
53. [HttpPost]
54. [ValidateAntiForgeryToken]
55. public ActionResult Create(Student student)
56. {
57. if (ModelState.IsValid)
58. {
59. db.Students.Add(student);
60. db.SaveChanges();
61. return RedirectToAction("Index");
62. }
63.
64. return View(student);
65. }
66.
67. //
68. // GET: /Student/Edit/5
69.
70. public ActionResult Edit(string id = null)
71. {
72. Student student = db.Students.Find(id);
73. if (student == null)
74. {
75. return HttpNotFound();
76. }
77. return View(student);
78. }
79.
80. //
81. // POST: /Student/Edit/5
82.
83. [HttpPost]
84. [ValidateAntiForgeryToken]
85. public ActionResult Edit(Student student)
86. {
87. if (ModelState.IsValid)
88. {
89. db.Entry(student).State = EntityState.Modified;
90. db.SaveChanges();
91. return RedirectToAction("Index");
92. }
93. return View(student);
94. }
95.
96. //
97. // GET: /Student/Delete/5
98.
99. public ActionResult Delete(string id = null)
100. {
101. Student student = db.Students.Find(id);
102. if (student == null)
103. {
104. return HttpNotFound();
105. }
106. return View(student);
107. }
108.
109. //
110. // POST: /Student/Delete/5
111.
112. [HttpPost, ActionName("Delete")]
113. [ValidateAntiForgeryToken]
114. public ActionResult DeleteConfirmed(string id)
115. {
116. Student student = db.Students.Find(id);
117. db.Students.Remove(student);
118. db.SaveChanges();
119. return RedirectToAction("Index");
120. }
121.
122. protected override void Dispose(bool disposing)
123. {
124. db.Dispose();
125. base.Dispose(disposing);
126. }
127. }
128. }
7.Step7: 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 }
);
}
8. Step8: Now press F5 to run the application, and you’ll see the list of all students we added in to 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 data base,
Similarly for Edit,
Change any field and press save.The change will be reflected in the list and data base,
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 .
Ad

More Related Content

Viewers also liked (12)

Web service as back end programming kemuning senja
Web service as back end programming kemuning senjaWeb service as back end programming kemuning senja
Web service as back end programming kemuning senja
alifha12
 
SIM Lanjut (ERP)
SIM Lanjut (ERP)SIM Lanjut (ERP)
SIM Lanjut (ERP)
alifha12
 
Evolution of Opera & Western Vocal Music
Evolution of Opera & Western Vocal MusicEvolution of Opera & Western Vocal Music
Evolution of Opera & Western Vocal Music
Peter Chris Bersick
 
11111
1111111111
11111
dianapamoc
 
PRINTED RFID USING SCREEN PRINTING
PRINTED RFID USING SCREEN PRINTINGPRINTED RFID USING SCREEN PRINTING
PRINTED RFID USING SCREEN PRINTING
Nita samantaray
 
Matri SIM Lanjut (Implementasi BPR)
Matri SIM Lanjut (Implementasi BPR)Matri SIM Lanjut (Implementasi BPR)
Matri SIM Lanjut (Implementasi BPR)
alifha12
 
Comparing Modern to Medieval Teenager Life
Comparing Modern to Medieval Teenager LifeComparing Modern to Medieval Teenager Life
Comparing Modern to Medieval Teenager Life
Peter Chris Bersick
 
Iso 12647 2
Iso 12647 2Iso 12647 2
Iso 12647 2
Nita samantaray
 
Psycholinguistics
PsycholinguisticsPsycholinguistics
Psycholinguistics
Icha Pebly Arma
 
Making It: Modern Music
Making It: Modern MusicMaking It: Modern Music
Making It: Modern Music
Peter Chris Bersick
 
SevenHills Hospital in Mumbai - PPT Presentation
SevenHills Hospital in Mumbai - PPT PresentationSevenHills Hospital in Mumbai - PPT Presentation
SevenHills Hospital in Mumbai - PPT Presentation
SevenHills Hospital
 
Revision of Psycholinguistics
Revision of PsycholinguisticsRevision of Psycholinguistics
Revision of Psycholinguistics
Icha Pebly Arma
 
Web service as back end programming kemuning senja
Web service as back end programming kemuning senjaWeb service as back end programming kemuning senja
Web service as back end programming kemuning senja
alifha12
 
SIM Lanjut (ERP)
SIM Lanjut (ERP)SIM Lanjut (ERP)
SIM Lanjut (ERP)
alifha12
 
Evolution of Opera & Western Vocal Music
Evolution of Opera & Western Vocal MusicEvolution of Opera & Western Vocal Music
Evolution of Opera & Western Vocal Music
Peter Chris Bersick
 
PRINTED RFID USING SCREEN PRINTING
PRINTED RFID USING SCREEN PRINTINGPRINTED RFID USING SCREEN PRINTING
PRINTED RFID USING SCREEN PRINTING
Nita samantaray
 
Matri SIM Lanjut (Implementasi BPR)
Matri SIM Lanjut (Implementasi BPR)Matri SIM Lanjut (Implementasi BPR)
Matri SIM Lanjut (Implementasi BPR)
alifha12
 
Comparing Modern to Medieval Teenager Life
Comparing Modern to Medieval Teenager LifeComparing Modern to Medieval Teenager Life
Comparing Modern to Medieval Teenager Life
Peter Chris Bersick
 
SevenHills Hospital in Mumbai - PPT Presentation
SevenHills Hospital in Mumbai - PPT PresentationSevenHills Hospital in Mumbai - PPT Presentation
SevenHills Hospital in Mumbai - PPT Presentation
SevenHills Hospital
 
Revision of Psycholinguistics
Revision of PsycholinguisticsRevision of Psycholinguistics
Revision of Psycholinguistics
Icha Pebly Arma
 

Similar to Mvc4 crud operations.-kemuning senja (20)

Learning MVC Part 3 Creating MVC Application with EntityFramework
Learning MVC Part 3 Creating MVC Application with EntityFrameworkLearning MVC Part 3 Creating MVC Application with EntityFramework
Learning MVC Part 3 Creating MVC Application with EntityFramework
Akhil Mittal
 
LearningMVCWithLINQToSQL
LearningMVCWithLINQToSQLLearningMVCWithLINQToSQL
LearningMVCWithLINQToSQL
Akhil Mittal
 
CodeIgniter 101 Tutorial
CodeIgniter 101 TutorialCodeIgniter 101 Tutorial
CodeIgniter 101 Tutorial
Konstantinos Magarisiotis
 
Mvc interview questions – deep dive jinal desai
Mvc interview questions – deep dive   jinal desaiMvc interview questions – deep dive   jinal desai
Mvc interview questions – deep dive jinal desai
jinaldesailive
 
Repository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity FrameworkRepository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity Framework
Akhil Mittal
 
Mvc acchitecture
Mvc acchitectureMvc acchitecture
Mvc acchitecture
laxmi.katkar
 
8-9-10. ASP_updated8-9-10. ASP_updated8-9-10. ASP_updated
8-9-10. ASP_updated8-9-10. ASP_updated8-9-10. ASP_updated8-9-10. ASP_updated8-9-10. ASP_updated8-9-10. ASP_updated
8-9-10. ASP_updated8-9-10. ASP_updated8-9-10. ASP_updated
dioduong345
 
ASP.NET Identity
ASP.NET IdentityASP.NET Identity
ASP.NET Identity
Suzanne Simmons
 
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
vchircu
 
An Overview of Entity Framework
An Overview of Entity FrameworkAn Overview of Entity Framework
An Overview of Entity Framework
iFour Technolab Pvt. Ltd.
 
MVC Design Pattern in JavaScript by ADMEC Multimedia Institute
MVC Design Pattern in JavaScript by ADMEC Multimedia InstituteMVC Design Pattern in JavaScript by ADMEC Multimedia Institute
MVC Design Pattern in JavaScript by ADMEC Multimedia Institute
Ravi Bhadauria
 
ASP.NET MVC3 RAD
ASP.NET MVC3 RADASP.NET MVC3 RAD
ASP.NET MVC3 RAD
Mădălin Ștefîrcă
 
Tightly coupled view (model bounded view)
Tightly coupled view (model bounded view)Tightly coupled view (model bounded view)
Tightly coupled view (model bounded view)
IT PROGRAMMING WORLD
 
Aspnet mvc tutorial_01_cs
Aspnet mvc tutorial_01_csAspnet mvc tutorial_01_cs
Aspnet mvc tutorial_01_cs
Alfa Gama Omega
 
Principles of MVC for Rails Developers
Principles of MVC for Rails DevelopersPrinciples of MVC for Rails Developers
Principles of MVC for Rails Developers
Edureka!
 
Overview of CSharp MVC3 and EF4
Overview of CSharp MVC3 and EF4Overview of CSharp MVC3 and EF4
Overview of CSharp MVC3 and EF4
Rich Helton
 
ASP.NET Core MVC with EF Core code first
ASP.NET Core MVC with EF Core code firstASP.NET Core MVC with EF Core code first
ASP.NET Core MVC with EF Core code first
Md. Aftab Uddin Kajal
 
Migrating from jQuery - Core Journey to Vanilla JS
Migrating from jQuery - Core Journey to Vanilla JSMigrating from jQuery - Core Journey to Vanilla JS
Migrating from jQuery - Core Journey to Vanilla JS
Andreas Nedbal
 
Generic Repository Pattern in MVC3 Application with Entity Framework
Generic Repository Pattern in MVC3 Application with Entity FrameworkGeneric Repository Pattern in MVC3 Application with Entity Framework
Generic Repository Pattern in MVC3 Application with Entity Framework
Akhil Mittal
 
Enterprise Level Application Architecture with Web APIs using Entity Framewor...
Enterprise Level Application Architecture with Web APIs using Entity Framewor...Enterprise Level Application Architecture with Web APIs using Entity Framewor...
Enterprise Level Application Architecture with Web APIs using Entity Framewor...
Akhil Mittal
 
Learning MVC Part 3 Creating MVC Application with EntityFramework
Learning MVC Part 3 Creating MVC Application with EntityFrameworkLearning MVC Part 3 Creating MVC Application with EntityFramework
Learning MVC Part 3 Creating MVC Application with EntityFramework
Akhil Mittal
 
LearningMVCWithLINQToSQL
LearningMVCWithLINQToSQLLearningMVCWithLINQToSQL
LearningMVCWithLINQToSQL
Akhil Mittal
 
Mvc interview questions – deep dive jinal desai
Mvc interview questions – deep dive   jinal desaiMvc interview questions – deep dive   jinal desai
Mvc interview questions – deep dive jinal desai
jinaldesailive
 
Repository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity FrameworkRepository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity Framework
Akhil Mittal
 
8-9-10. ASP_updated8-9-10. ASP_updated8-9-10. ASP_updated
8-9-10. ASP_updated8-9-10. ASP_updated8-9-10. ASP_updated8-9-10. ASP_updated8-9-10. ASP_updated8-9-10. ASP_updated
8-9-10. ASP_updated8-9-10. ASP_updated8-9-10. ASP_updated
dioduong345
 
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
vchircu
 
MVC Design Pattern in JavaScript by ADMEC Multimedia Institute
MVC Design Pattern in JavaScript by ADMEC Multimedia InstituteMVC Design Pattern in JavaScript by ADMEC Multimedia Institute
MVC Design Pattern in JavaScript by ADMEC Multimedia Institute
Ravi Bhadauria
 
Tightly coupled view (model bounded view)
Tightly coupled view (model bounded view)Tightly coupled view (model bounded view)
Tightly coupled view (model bounded view)
IT PROGRAMMING WORLD
 
Aspnet mvc tutorial_01_cs
Aspnet mvc tutorial_01_csAspnet mvc tutorial_01_cs
Aspnet mvc tutorial_01_cs
Alfa Gama Omega
 
Principles of MVC for Rails Developers
Principles of MVC for Rails DevelopersPrinciples of MVC for Rails Developers
Principles of MVC for Rails Developers
Edureka!
 
Overview of CSharp MVC3 and EF4
Overview of CSharp MVC3 and EF4Overview of CSharp MVC3 and EF4
Overview of CSharp MVC3 and EF4
Rich Helton
 
ASP.NET Core MVC with EF Core code first
ASP.NET Core MVC with EF Core code firstASP.NET Core MVC with EF Core code first
ASP.NET Core MVC with EF Core code first
Md. Aftab Uddin Kajal
 
Migrating from jQuery - Core Journey to Vanilla JS
Migrating from jQuery - Core Journey to Vanilla JSMigrating from jQuery - Core Journey to Vanilla JS
Migrating from jQuery - Core Journey to Vanilla JS
Andreas Nedbal
 
Generic Repository Pattern in MVC3 Application with Entity Framework
Generic Repository Pattern in MVC3 Application with Entity FrameworkGeneric Repository Pattern in MVC3 Application with Entity Framework
Generic Repository Pattern in MVC3 Application with Entity Framework
Akhil Mittal
 
Enterprise Level Application Architecture with Web APIs using Entity Framewor...
Enterprise Level Application Architecture with Web APIs using Entity Framewor...Enterprise Level Application Architecture with Web APIs using Entity Framewor...
Enterprise Level Application Architecture with Web APIs using Entity Framewor...
Akhil Mittal
 
Ad

Recently uploaded (20)

Kubernetes_101_Zero_to_Platform_Engineer.pptx
Kubernetes_101_Zero_to_Platform_Engineer.pptxKubernetes_101_Zero_to_Platform_Engineer.pptx
Kubernetes_101_Zero_to_Platform_Engineer.pptx
CloudScouts
 
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
Andre Hora
 
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Ranjan Baisak
 
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage DashboardsAdobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
BradBedford3
 
Adobe After Effects Crack FREE FRESH version 2025
Adobe After Effects Crack FREE FRESH version 2025Adobe After Effects Crack FREE FRESH version 2025
Adobe After Effects Crack FREE FRESH version 2025
kashifyounis067
 
Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]
saniaaftab72555
 
How can one start with crypto wallet development.pptx
How can one start with crypto wallet development.pptxHow can one start with crypto wallet development.pptx
How can one start with crypto wallet development.pptx
laravinson24
 
Societal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainabilitySocietal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainability
Jordi Cabot
 
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
Egor Kaleynik
 
The Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdfThe Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdf
drewplanas10
 
Explaining GitHub Actions Failures with Large Language Models Challenges, In...
Explaining GitHub Actions Failures with Large Language Models Challenges, In...Explaining GitHub Actions Failures with Large Language Models Challenges, In...
Explaining GitHub Actions Failures with Large Language Models Challenges, In...
ssuserb14185
 
Download YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full ActivatedDownload YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full Activated
saniamalik72555
 
Exploring Code Comprehension in Scientific Programming: Preliminary Insight...
Exploring Code Comprehension  in Scientific Programming:  Preliminary Insight...Exploring Code Comprehension  in Scientific Programming:  Preliminary Insight...
Exploring Code Comprehension in Scientific Programming: Preliminary Insight...
University of Hawai‘i at Mānoa
 
Expand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchangeExpand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchange
Fexle Services Pvt. Ltd.
 
Adobe Illustrator Crack FREE Download 2025 Latest Version
Adobe Illustrator Crack FREE Download 2025 Latest VersionAdobe Illustrator Crack FREE Download 2025 Latest Version
Adobe Illustrator Crack FREE Download 2025 Latest Version
kashifyounis067
 
Meet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Meet the Agents: How AI Is Learning to Think, Plan, and CollaborateMeet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Meet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Maxim Salnikov
 
Landscape of Requirements Engineering for/by AI through Literature Review
Landscape of Requirements Engineering for/by AI through Literature ReviewLandscape of Requirements Engineering for/by AI through Literature Review
Landscape of Requirements Engineering for/by AI through Literature Review
Hironori Washizaki
 
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
Andre Hora
 
Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)
Allon Mureinik
 
Secure Test Infrastructure: The Backbone of Trustworthy Software Development
Secure Test Infrastructure: The Backbone of Trustworthy Software DevelopmentSecure Test Infrastructure: The Backbone of Trustworthy Software Development
Secure Test Infrastructure: The Backbone of Trustworthy Software Development
Shubham Joshi
 
Kubernetes_101_Zero_to_Platform_Engineer.pptx
Kubernetes_101_Zero_to_Platform_Engineer.pptxKubernetes_101_Zero_to_Platform_Engineer.pptx
Kubernetes_101_Zero_to_Platform_Engineer.pptx
CloudScouts
 
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
TestMigrationsInPy: A Dataset of Test Migrations from Unittest to Pytest (MSR...
Andre Hora
 
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Ranjan Baisak
 
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage DashboardsAdobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
Adobe Marketo Engage Champion Deep Dive - SFDC CRM Synch V2 & Usage Dashboards
BradBedford3
 
Adobe After Effects Crack FREE FRESH version 2025
Adobe After Effects Crack FREE FRESH version 2025Adobe After Effects Crack FREE FRESH version 2025
Adobe After Effects Crack FREE FRESH version 2025
kashifyounis067
 
Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]
saniaaftab72555
 
How can one start with crypto wallet development.pptx
How can one start with crypto wallet development.pptxHow can one start with crypto wallet development.pptx
How can one start with crypto wallet development.pptx
laravinson24
 
Societal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainabilitySocietal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainability
Jordi Cabot
 
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
Egor Kaleynik
 
The Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdfThe Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdf
drewplanas10
 
Explaining GitHub Actions Failures with Large Language Models Challenges, In...
Explaining GitHub Actions Failures with Large Language Models Challenges, In...Explaining GitHub Actions Failures with Large Language Models Challenges, In...
Explaining GitHub Actions Failures with Large Language Models Challenges, In...
ssuserb14185
 
Download YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full ActivatedDownload YouTube By Click 2025 Free Full Activated
Download YouTube By Click 2025 Free Full Activated
saniamalik72555
 
Exploring Code Comprehension in Scientific Programming: Preliminary Insight...
Exploring Code Comprehension  in Scientific Programming:  Preliminary Insight...Exploring Code Comprehension  in Scientific Programming:  Preliminary Insight...
Exploring Code Comprehension in Scientific Programming: Preliminary Insight...
University of Hawai‘i at Mānoa
 
Expand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchangeExpand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchange
Fexle Services Pvt. Ltd.
 
Adobe Illustrator Crack FREE Download 2025 Latest Version
Adobe Illustrator Crack FREE Download 2025 Latest VersionAdobe Illustrator Crack FREE Download 2025 Latest Version
Adobe Illustrator Crack FREE Download 2025 Latest Version
kashifyounis067
 
Meet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Meet the Agents: How AI Is Learning to Think, Plan, and CollaborateMeet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Meet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Maxim Salnikov
 
Landscape of Requirements Engineering for/by AI through Literature Review
Landscape of Requirements Engineering for/by AI through Literature ReviewLandscape of Requirements Engineering for/by AI through Literature Review
Landscape of Requirements Engineering for/by AI through Literature Review
Hironori Washizaki
 
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
What Do Contribution Guidelines Say About Software Testing? (MSR 2025)
Andre Hora
 
Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)
Allon Mureinik
 
Secure Test Infrastructure: The Backbone of Trustworthy Software Development
Secure Test Infrastructure: The Backbone of Trustworthy Software DevelopmentSecure Test Infrastructure: The Backbone of Trustworthy Software Development
Secure Test Infrastructure: The Backbone of Trustworthy Software Development
Shubham Joshi
 
Ad

Mvc4 crud operations.-kemuning senja

  • 1. Complete CRUD Operations in MVC 4 using Entity Framework 5 without writing single 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 on 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.
  • 2. Hope this gives a glimpse of an ORM and EntityFramework. III) MVC Application: 1. Step1: Create a data base 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')
  • 3. 2. Step2: Open your Visual Studio (Visual Studio Version should be greater than or equal to 12) and add an MVC Internet application,
  • 5. I have given it a name “KnockoutWithMVC4”. 3. Step3: 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 click the project, select manage nugget packages and search and install Entity Framework,
  • 7. 4. 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,
  • 9. Generate model from data base, select your server and LearningKO data base name, the connection string will automatically be added to your Web.Config, name that connection string as LearningKOEntities.
  • 10. Select tables to be added to the model. In our case it’s Student Table.
  • 11. 5. Step5: 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,
  • 12.  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 outr 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.
  • 13. 6. Step6: We see out student controller prepared with all the CRUD operation actions as shown below, 7. using System; 8. using System.Collections.Generic; 9. using System.Data; 10. using System.Data.Entity; 11. using System.Linq; 12. using System.Web; 13. using System.Web.Mvc; 14. 15. namespace KnockoutWithMVC4.Controllers 16. { 17. public class StudentController : Controller 18. { 19. private LearningKOEntities db = new LearningKOEntities(); 20. 21. // 22. // GET: /Student/ 23. 24. public ActionResult Index() 25. { 26. return View(db.Students.ToList()); 27. } 28. 29. // 30. // GET: /Student/Details/5 31. 32. public ActionResult Details(string id = null) 33. { 34. Student student = db.Students.Find(id); 35. if (student == null) 36. {
  • 14. 37. return HttpNotFound(); 38. } 39. return View(student); 40. } 41. 42. // 43. // GET: /Student/Create 44. 45. public ActionResult Create() 46. { 47. return View(); 48. } 49. 50. // 51. // POST: /Student/Create 52. 53. [HttpPost] 54. [ValidateAntiForgeryToken] 55. public ActionResult Create(Student student) 56. { 57. if (ModelState.IsValid) 58. { 59. db.Students.Add(student); 60. db.SaveChanges(); 61. return RedirectToAction("Index"); 62. } 63. 64. return View(student); 65. } 66. 67. // 68. // GET: /Student/Edit/5 69. 70. public ActionResult Edit(string id = null) 71. { 72. Student student = db.Students.Find(id); 73. if (student == null) 74. { 75. return HttpNotFound(); 76. } 77. return View(student); 78. } 79. 80. // 81. // POST: /Student/Edit/5 82. 83. [HttpPost] 84. [ValidateAntiForgeryToken] 85. public ActionResult Edit(Student student) 86. { 87. if (ModelState.IsValid) 88. { 89. db.Entry(student).State = EntityState.Modified; 90. db.SaveChanges(); 91. return RedirectToAction("Index"); 92. } 93. return View(student); 94. } 95. 96. // 97. // GET: /Student/Delete/5 98.
  • 15. 99. public ActionResult Delete(string id = null) 100. { 101. Student student = db.Students.Find(id); 102. if (student == null) 103. { 104. return HttpNotFound(); 105. } 106. return View(student); 107. } 108. 109. // 110. // POST: /Student/Delete/5 111. 112. [HttpPost, ActionName("Delete")] 113. [ValidateAntiForgeryToken] 114. public ActionResult DeleteConfirmed(string id) 115. { 116. Student student = db.Students.Find(id); 117. db.Students.Remove(student); 118. db.SaveChanges(); 119. return RedirectToAction("Index"); 120. } 121. 122. protected override void Dispose(bool disposing) 123. { 124. db.Dispose(); 125. base.Dispose(disposing); 126. } 127. } 128. } 7.Step7: Open App_Start folder and, change the name of controller from Home to Student,
  • 16. 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 } ); } 8. Step8: Now press F5 to run the application, and you’ll see the list of all students we added in to 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.
  • 17. Now you can perform all the operations on this list.
  • 18. 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 ,
  • 19. We see that the student is created successfully and added to the list, In data base,
  • 20. Similarly for Edit, Change any field and press save.The change will be reflected in the list and data base,
  • 23. 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 .