mvc4 crud operations.-kemuning senja

23
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.

Upload: alifha12

Post on 13-Apr-2017

126 views

Category:

Software


0 download

TRANSCRIPT

Page 1: Mvc4 crud operations.-kemuning senja

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.

Page 2: Mvc4 crud operations.-kemuning senja

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')

Page 3: Mvc4 crud operations.-kemuning senja

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

Page 4: Mvc4 crud operations.-kemuning senja
Page 5: 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,

Page 6: Mvc4 crud operations.-kemuning senja
Page 7: 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,

Page 8: Mvc4 crud operations.-kemuning senja
Page 9: 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.

Page 10: Mvc4 crud operations.-kemuning senja

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

Page 11: Mvc4 crud operations.-kemuning senja

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,

Page 12: Mvc4 crud operations.-kemuning senja

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.

Page 13: Mvc4 crud operations.-kemuning senja

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. {

Page 14: Mvc4 crud operations.-kemuning senja

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.

Page 15: Mvc4 crud operations.-kemuning senja

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,

Page 16: Mvc4 crud operations.-kemuning senja

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.

Page 17: Mvc4 crud operations.-kemuning senja

Now you can perform all the operations on this list.

Page 18: Mvc4 crud operations.-kemuning senja

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 ,

Page 19: Mvc4 crud operations.-kemuning senja

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

In data base,

Page 20: Mvc4 crud operations.-kemuning senja

Similarly for Edit,

Change any field and press save.The change will be reflected in the list and data base,

Page 21: Mvc4 crud operations.-kemuning senja

For Delete,

Student Deleted.

Page 22: Mvc4 crud operations.-kemuning senja

And in database,

Page 23: Mvc4 crud operations.-kemuning senja

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 .