{"id":4586,"date":"2023-02-24T10:14:51","date_gmt":"2023-02-24T10:14:51","guid":{"rendered":"https:\/\/isophal.com\/?p=4586"},"modified":"2023-02-24T10:14:52","modified_gmt":"2023-02-24T10:14:52","slug":"crud-operations-using-entity-framework-in-asp-net-mvc","status":"publish","type":"post","link":"https:\/\/isophal.com\/news\/2023\/02\/24\/4586.html\/","title":{"rendered":"<strong>CRUD Operations using Entity Framework in ASP.NET MVC<\/strong>"},"content":{"rendered":"\n<p>In this and in few upcoming articles, I am going to discuss how to perform\u00a0<strong>CRUD operations using Entity Framework in ASP.NET MVC<\/strong>\u00a0application. Please read our previous article where we discussed how to\u00a0<a href=\"https:\/\/dotnettutorials.net\/lesson\/deleting-database-records-in-asp-net-mvc\/\"><strong>Delete Database Records in ASP.NET MVC<\/strong><\/a>\u00a0Application with some examples.<\/p>\n\n\n\n<h5 class=\"wp-block-heading\"><strong>Database Tables used in this Demo:<\/strong><\/h5>\n\n\n\n<p>In this demo, we are going to use the following\u00a0<strong>Department\u00a0<\/strong>and\u00a0<strong>Employee<\/strong>\u00a0table. So, please use the below SQL script to create and populate these 2 tables<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Create table Department\r\n(\r\n  Id int primary key identity,\r\n  Name nvarchar(50)\r\n)\r\nInsert into Department values('IT')\r\nInsert into Department values('HR')\r\nInsert into Department values('Payroll')\r\nCreate table Employee\r\n(\r\n  EmployeeId int Primary Key Identity(1,1),\r\n  Name nvarchar(50),\r\n  Gender nvarchar(10),\r\n  City nvarchar(50),\r\n  Salary decimal(18,2),\r\n  DepartmentId int\r\n)\r\nAlter table Employee add foreign key (DepartmentId) references Department(Id)\r\nInsert into Employee values('Mark','Male','London',1000,1)\r\nInsert into Employee values('John','Male','Chennai',2000,3)\r\nInsert into Employee values('Mary','Female','New York',3000,3)\r\nInsert into Employee values('Mike','Male','Sydeny',4000,2)\r\nInsert into Employee values('Scott','Male','London',3000,1)\r\nInsert into Employee values('Pam','Female','Falls Church',2000,2)\r\nInsert into Employee values('Todd','Male','Sydney',1000,1)\r\nInsert into Employee values('Ben','Male','New Delhi',4000,2)\r\nInsert into Employee values('Sara','Female','London',5000,1)<\/code><\/pre>\n\n\n\n<h5 class=\"wp-block-heading\"><strong>Create a new ASP.NET MVC 5 Web application:<\/strong><\/h5>\n\n\n\n<p>Open&nbsp;<strong>File =&gt; New =&gt;Project<\/strong>&nbsp;and then&nbsp;select&nbsp;<strong>Installed =&gt; Templates =&gt; Visual C#.&nbsp;<\/strong>Then select&nbsp;<strong>ASP.NET Web Application<\/strong>. Provide&nbsp;the project name and location where you want to save your application and finally click on the&nbsp;<strong>OK<\/strong>&nbsp;button as shown in the below image.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/dotnettutorials.net\/wp-content\/uploads\/2018\/07\/CRUD-Operations-using-Entity-Framework-in-ASP.NET-MVC.png\" alt=\"CRUD Operations using Entity Framework in ASP.NET MVC\" class=\"wp-image-4652\" title=\"CRUD Operations using Entity Framework in ASP.NET MVC\"\/><\/figure>\n\n\n\n<p>From the next screen that is from select a template screen, select&nbsp;<strong>Empty<\/strong>&nbsp;as the project template.&nbsp;From add folder and core reference section check the&nbsp;<strong>MVC<\/strong>&nbsp;checkbox and click on&nbsp;<strong>OK<\/strong>&nbsp;as shown below.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/dotnettutorials.net\/wp-content\/uploads\/2018\/07\/Selecting-Project-Template-in-ASP.NET-MVC-Application.png\" alt=\"Selecting Project Template in ASP.NET MVC Application\" class=\"wp-image-4653\" title=\"Selecting Project Template in ASP.NET MVC Application\"\/><\/figure>\n\n\n\n<p>Once you click on the OK button, it will take some time to create the project for us.<\/p>\n\n\n\n<h5 class=\"wp-block-heading\"><strong>Adding ADO.NET Entity Data Model<\/strong><\/h5>\n\n\n\n<p>Right-click on Models folder then select&nbsp;<strong>Add =&gt; New Item<\/strong>&nbsp;from the context menu that will open the&nbsp;<strong>Add New Item<\/strong>&nbsp;window.&nbsp;Select the&nbsp;<strong>Data<\/strong>&nbsp;tab from the left panel and then choose&nbsp;<strong>ADO.NET Entity Data Model<\/strong>&nbsp;from the middle panel. Provide a meaningful name for your data model and click on the&nbsp;<strong>Add<\/strong>&nbsp;button as shown in the below image.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/dotnettutorials.net\/wp-content\/uploads\/2018\/07\/Adding-ADO.NET-Entity-Data-Model-in-ASP.NET-MVC-Application.png\" alt=\"Adding ADO.NET Entity Data Model in ASP.NET MVC Application\" class=\"wp-image-4654\" title=\"Adding ADO.NET Entity Data Model in ASP.NET MVC Application\"\/><\/figure>\n\n\n\n<h5 class=\"wp-block-heading\"><strong>Selecting The Entity Framework Approach to interact with the database.<\/strong><\/h5>\n\n\n\n<p>Once you click on the Add button it will ask you to choose the entity framework approach. Here, we are going to use the database first approach as we already created the required database tables. So, from the Entity Data Model Wizard, select \u201c<strong>Generate from database<\/strong>\u201d option and click \u201c<strong>Next<\/strong>\u201d as shown below.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/dotnettutorials.net\/wp-content\/uploads\/2018\/07\/Selecting-Database-First-Approach-in-Entity-Framework.png\" alt=\"Selecting Database First Approach in Entity Framework\" class=\"wp-image-4655\" title=\"Selecting Database First Approach in Entity Framework\"\/><figcaption class=\"wp-element-caption\"><strong>Creating Database Connection:<\/strong><br>On\u00a0\u201c<strong>Choose your data connection screen<\/strong>\u201d and click on the \u201c<strong>New Connection<\/strong>\u201d button which will open the connection properties window. Here, we are going to interact with the SQL Server database. So, from the Data Source select\u00a0<strong>Microsoft SQL Server (SqlClient)<\/strong>. Provide your SQL Server name. Choose the Authentication type. Here, I am choosing\u00a0<strong>Windows Authentication<\/strong>. Then select the database to which you are going to interact from the\u00a0<strong>select or enter a database name<\/strong>\u00a0drop-down list. Finally,\u00a0click on the \u201c<strong>OK<\/strong>\u201d as shown below.<br><img loading=\"lazy\" decoding=\"async\" width=\"546\" height=\"758\" srcset=\"https:\/\/dotnettutorials.net\/wp-content\/uploads\/2018\/07\/Creating-Database-Connection-in-Entity-Framework-Database-First-Approach.png 627w, https:\/\/dotnettutorials.net\/wp-content\/uploads\/2018\/07\/Creating-Database-Connection-in-Entity-Framework-Database-First-Approach-216x300.png 216w\" src=\"https:\/\/dotnettutorials.net\/wp-content\/uploads\/2018\/07\/Creating-Database-Connection-in-Entity-Framework-Database-First-Approach.png\" alt=\"Creating Database Connection in Entity Framework Database First Approach\"><br>Then provide a meaningful connection string name such as \u201c<strong>EmployeeDBContext<\/strong>\u201d and click on the \u201c<strong>Next<\/strong>\u201d button as shown below.<br><img loading=\"lazy\" decoding=\"async\" width=\"546\" height=\"562\" srcset=\"https:\/\/dotnettutorials.net\/wp-content\/uploads\/2018\/07\/CRUD-Operations-using-Entity-Framework-in-ASP.NET-MVC-1.png 688w, https:\/\/dotnettutorials.net\/wp-content\/uploads\/2018\/07\/CRUD-Operations-using-Entity-Framework-in-ASP.NET-MVC-1-292x300.png 292w\" src=\"https:\/\/dotnettutorials.net\/wp-content\/uploads\/2018\/07\/CRUD-Operations-using-Entity-Framework-in-ASP.NET-MVC-1.png\" alt=\"CRUD Operations using Entity Framework in ASP.NET MVC\"><br><strong>Choose Entity Framework Version:<\/strong><br>Here, we are going to use Entity Framework 6. So, from the Choose Your Version screen, choose the\u00a0<strong>Entity framework 6.x\u00a0<\/strong>\u00a0and click on the\u00a0<strong>Next<\/strong>\u00a0button as shown below.<br><img loading=\"lazy\" decoding=\"async\" width=\"511\" height=\"528\" srcset=\"https:\/\/dotnettutorials.net\/wp-content\/uploads\/2018\/07\/Selecting-Entity-Framework-Version-in-ASP.NET-MVC-Application.png 681w, https:\/\/dotnettutorials.net\/wp-content\/uploads\/2018\/07\/Selecting-Entity-Framework-Version-in-ASP.NET-MVC-Application-290x300.png 290w\" src=\"https:\/\/dotnettutorials.net\/wp-content\/uploads\/2018\/07\/Selecting-Entity-Framework-Version-in-ASP.NET-MVC-Application.png\" alt=\"Selecting Entity Framework Version in ASP.NET MVC Application\"><br><strong>Selecting Database Objects and Settings:<\/strong><br>On \u201c<strong>Choose your database objects and Settings<\/strong>\u201d screen, expand the \u201c<strong>Tables<\/strong>\u201d and then select \u201c<strong>Department<\/strong>\u201d and \u201c<strong>Employee<\/strong>\u201d tables. Set Model Namespace as\u00a0<strong>Models<\/strong>\u00a0and click on the \u201c<strong>Finish<\/strong>\u201d button as shown in the below image.<br><img loading=\"lazy\" decoding=\"async\" width=\"479\" height=\"564\" srcset=\"https:\/\/dotnettutorials.net\/wp-content\/uploads\/2018\/07\/Selecting-Database-Objects-and-Settings-in-Entity-Framework.png 608w, https:\/\/dotnettutorials.net\/wp-content\/uploads\/2018\/07\/Selecting-Database-Objects-and-Settings-in-Entity-Framework-255x300.png 255w\" src=\"https:\/\/dotnettutorials.net\/wp-content\/uploads\/2018\/07\/Selecting-Database-Objects-and-Settings-in-Entity-Framework.png\" alt=\"Selecting Database Objects and Settings in Entity Framework\"><br>At this point, we should have\u00a0Department<strong>\u00a0<\/strong>and\u00a0Employee\u00a0entities generated as shown below.<br><img loading=\"lazy\" decoding=\"async\" width=\"402\" height=\"264\" srcset=\"https:\/\/dotnettutorials.net\/wp-content\/uploads\/2018\/07\/CRUD-Operations-using-Entity-Framework-in-ASP.NET-MVC-Application.png 467w, https:\/\/dotnettutorials.net\/wp-content\/uploads\/2018\/07\/CRUD-Operations-using-Entity-Framework-in-ASP.NET-MVC-Application-300x197.png 300w\" src=\"https:\/\/dotnettutorials.net\/wp-content\/uploads\/2018\/07\/CRUD-Operations-using-Entity-Framework-in-ASP.NET-MVC-Application.png\" alt=\"CRUD Operations using Entity Framework in ASP.NET MVC Application\"><\/figcaption><\/figure>\n\n\n\n<h5 class=\"wp-block-heading\">Creating MVC 5 Controller:<\/h5>\n\n\n\n<p>Right-click on the \u201c<strong>Controllers<\/strong>\u201d folder and select&nbsp;<strong>Add \u2013 Controller<\/strong>&nbsp;from the context menu. Then select&nbsp;<strong>MVC 5 Controller with views, using Entity Framework<\/strong>&nbsp;and click on the&nbsp;<strong>Add<\/strong>&nbsp;button as shown in the below image.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/dotnettutorials.net\/wp-content\/uploads\/2018\/07\/Creating-MVC-5-Controller-using-Entity-Framework.png\" alt=\"Creating MVC 5 Controller using Entity Framework\" class=\"wp-image-4661\" title=\"Creating MVC 5 Controller using Entity Framework\"\/><\/figure>\n\n\n\n<p><strong>On the next screen set the below details<\/strong><\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Model class = Employee (CRUD_Using_EF.Models)<\/strong><\/li>\n\n\n\n<li><strong>Data Context Class = EmployeeDBContext(CRUD_Using_EF.Models)<\/strong><\/li>\n\n\n\n<li><strong>Controller Name = EmployeeController<\/strong><\/li>\n\n\n\n<li><strong>Rest values are as it is and click on the Add button as shown in the below image<\/strong><\/li>\n<\/ol>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/dotnettutorials.net\/wp-content\/uploads\/2018\/07\/Setting-Controller-Properties-to-Create-Views-and-Action-Methods.png\" alt=\"Setting Controller Properties to Create Views and Action Methods\" class=\"wp-image-4662\" title=\"Setting Controller Properties to Create Views and Action Methods\"\/><\/figure>\n\n\n\n<p>At this point, we should have the following files automatically added.<\/p>\n\n\n\n<p><strong>EmployeeController.cs<\/strong>&nbsp;file in \u201c<strong>Controllers<\/strong>\u201d folder.&nbsp;<strong>Index, Create, Edit, Detail and Delete<\/strong>&nbsp;views in the \u201c<strong>Employee<\/strong>\u201d folder which is inside the Views folder.<\/p>\n\n\n\n<h5 class=\"wp-block-heading\"><strong>Below is the EmployeeController code<\/strong><\/h5>\n\n\n\n<pre class=\"wp-block-code\"><code>namespace CRUD_Using_EF.Controllers\r\n{\r\n    public class EmployeeController : Controller\r\n    {\r\n        private EmployeeDBContext db = new EmployeeDBContext();\r\n\r\n        \/\/ GET: Employee\r\n        public ActionResult Index()\r\n        {\r\n            var employees = db.Employees.Include(e => e.Department);\r\n            return View(employees.ToList());\r\n        }\r\n\r\n        \/\/ GET: Employee\/Details\/5\r\n        public ActionResult Details(int? id)\r\n        {\r\n            if (id == null)\r\n            {\r\n                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);\r\n            }\r\n            Employee employee = db.Employees.Find(id);\r\n            if (employee == null)\r\n            {\r\n                return HttpNotFound();\r\n            }\r\n            return View(employee);\r\n        }\r\n\r\n        \/\/ GET: Employee\/Create\r\n        public ActionResult Create()\r\n        {\r\n            ViewBag.DepartmentId = new SelectList(db.Departments, \"Id\", \"Name\");\r\n            return View();\r\n        }\r\n\r\n        \/\/ POST: Employee\/Create\r\n        \/\/ To protect from overposting attacks, please enable the specific properties you want to bind to, for \r\n        \/\/ more details see http:\/\/go.microsoft.com\/fwlink\/?LinkId=317598.\r\n        &#91;HttpPost]\r\n        &#91;ValidateAntiForgeryToken]\r\n        public ActionResult Create(&#91;Bind(Include = \"EmployeeId,Name,Gender,City,Salary,DepartmentId\")] Employee employee)\r\n        {\r\n            if (ModelState.IsValid)\r\n            {\r\n                db.Employees.Add(employee);\r\n                db.SaveChanges();\r\n                return RedirectToAction(\"Index\");\r\n            }\r\n\r\n            ViewBag.DepartmentId = new SelectList(db.Departments, \"Id\", \"Name\", employee.DepartmentId);\r\n            return View(employee);\r\n        }\r\n\r\n        \/\/ GET: Employee\/Edit\/5\r\n        public ActionResult Edit(int? id)\r\n        {\r\n            if (id == null)\r\n            {\r\n                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);\r\n            }\r\n            Employee employee = db.Employees.Find(id);\r\n            if (employee == null)\r\n            {\r\n                return HttpNotFound();\r\n            }\r\n            ViewBag.DepartmentId = new SelectList(db.Departments, \"Id\", \"Name\", employee.DepartmentId);\r\n            return View(employee);\r\n        }\r\n\r\n        \/\/ POST: Employee\/Edit\/5\r\n        \/\/ To protect from overposting attacks, please enable the specific properties you want to bind to, for \r\n        \/\/ more details see http:\/\/go.microsoft.com\/fwlink\/?LinkId=317598.\r\n        &#91;HttpPost]\r\n        &#91;ValidateAntiForgeryToken]\r\n        public ActionResult Edit(&#91;Bind(Include = \"EmployeeId,Name,Gender,City,Salary,DepartmentId\")] Employee employee)\r\n        {\r\n            if (ModelState.IsValid)\r\n            {\r\n                db.Entry(employee).State = EntityState.Modified;\r\n                db.SaveChanges();\r\n                return RedirectToAction(\"Index\");\r\n            }\r\n            ViewBag.DepartmentId = new SelectList(db.Departments, \"Id\", \"Name\", employee.DepartmentId);\r\n            return View(employee);\r\n        }\r\n\r\n        \/\/ GET: Employee\/Delete\/5\r\n        public ActionResult Delete(int? id)\r\n        {\r\n            if (id == null)\r\n            {\r\n                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);\r\n            }\r\n            Employee employee = db.Employees.Find(id);\r\n            if (employee == null)\r\n            {\r\n                return HttpNotFound();\r\n            }\r\n            return View(employee);\r\n        }\r\n\r\n        \/\/ POST: Employee\/Delete\/5\r\n        &#91;HttpPost, ActionName(\"Delete\")]\r\n        &#91;ValidateAntiForgeryToken]\r\n        public ActionResult DeleteConfirmed(int id)\r\n        {\r\n            Employee employee = db.Employees.Find(id);\r\n            db.Employees.Remove(employee);\r\n            db.SaveChanges();\r\n            return RedirectToAction(\"Index\");\r\n        }\r\n\r\n        protected override void Dispose(bool disposing)\r\n        {\r\n            if (disposing)\r\n            {\r\n                db.Dispose();\r\n            }\r\n            base.Dispose(disposing);\r\n        }\r\n    }\r\n}<\/code><\/pre>\n\n\n\n<p>At this point if you run the application you will get an error stating \u2013&nbsp;<strong>The resource cannot be found<\/strong>. This is because by default the application goes to the \u201c<strong>Home<\/strong>\u201d controller and \u201c<strong>Index<\/strong>\u201d action.&nbsp;To fix this,&nbsp;open \u201c<strong>RouteConfig.cs<\/strong>\u201d file from the \u201cApp_Start\u201d folder and set the&nbsp;controller as \u201c<strong>Employee<\/strong>\u201d as shown below.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/dotnettutorials.net\/wp-content\/uploads\/2018\/07\/RouteConfig-File-in-ASP.NET-MVC-Application.png\" alt=\"RouteConfig File in ASP.NET MVC Application\" class=\"wp-image-4663\" title=\"RouteConfig File in ASP.NET MVC Application\"\/><\/figure>\n\n\n\n<p>Run the application again. Notice that all the employees are listed on the index view. We can also create a new employee, edit an employee, view their full details and delete an employee as well. However, there are a few issues with each of the views which we will address in our upcoming articles.<\/p>\n\n\n\n<p>In our next article, I am going to discuss what are the issues associated with the&nbsp;<strong><a href=\"https:\/\/dotnettutorials.net\/lesson\/customizing-auto-generated-index-and-create-view\/\">Index view and how will solve this<\/a><\/strong>.&nbsp;Here, in this article, I try to explain how to perform&nbsp;<strong>CRUD operations using Entity Framework in ASP.NET MVC<\/strong>&nbsp;application. I hope this article will help you with your needs. I would like to have your feedback. Please post your feedback, question, or comments about this article.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this and in few upcoming articles,&hellip;<\/p>\n","protected":false},"author":1,"featured_media":4587,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[189,140],"tags":[191,579,576,577],"class_list":["post-4586","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-asp-net","category-programming","tag-asp-net","tag-crud-operations","tag-entity-framework","tag-mvc"],"_links":{"self":[{"href":"https:\/\/isophal.com\/news\/wp-json\/wp\/v2\/posts\/4586","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/isophal.com\/news\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/isophal.com\/news\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/isophal.com\/news\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/isophal.com\/news\/wp-json\/wp\/v2\/comments?post=4586"}],"version-history":[{"count":1,"href":"https:\/\/isophal.com\/news\/wp-json\/wp\/v2\/posts\/4586\/revisions"}],"predecessor-version":[{"id":4588,"href":"https:\/\/isophal.com\/news\/wp-json\/wp\/v2\/posts\/4586\/revisions\/4588"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/isophal.com\/news\/wp-json\/wp\/v2\/media\/4587"}],"wp:attachment":[{"href":"https:\/\/isophal.com\/news\/wp-json\/wp\/v2\/media?parent=4586"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/isophal.com\/news\/wp-json\/wp\/v2\/categories?post=4586"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/isophal.com\/news\/wp-json\/wp\/v2\/tags?post=4586"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}