Hello Friends, In this tutorial, I am going to show you how to perform CRUD operation using Entity Framework in ASP.NET MVC. We have already discussed Entity Framework in our previous session. Let’s Start the session.
Introduction:
Here I will create a simple example to perform CRUD operation using Entity Framework in ASP.NET MVC without writing a single line of code. Entity Framework is ORM framework that eliminates the need of accessive line of code for any database operation.
CRUD Operation using Entity Framework in ASP.NET MVC:
Create Database:
Open SQL Server and Create a database called EntityDemo.
CREATE DATABASE EntityDemo
Create an Employee table. Here is the script.
USE [EntityDemo] GO SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO SET ANSI_PADDING ON GO CREATE TABLE [dbo].[Employee]( [EmployeeID] [varchar](100) NOT NULL, [Name] [varchar](150) NULL, [Address] [varchar](100) NULL, [Salary] [float] NULL, CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED ( [EmployeeID] 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 SET ANSI_PADDING OFF GO
Insert few records into Employee table.
INSERT INTO [dbo].[Employee](EmployeeID,Name,Address,Salary) VALUES('E001','Manish Kumar','New Delhi',10000) INSERT INTO [dbo].[Employee](EmployeeID,Name,Address,Salary) VALUES('E002','Abhishek Kumar','Chennai',20000) INSERT INTO [dbo].[Employee](EmployeeID,Name,Address,Salary) VALUES('E003','Nitesh Singh','Noida',25000) INSERT INTO [dbo].[Employee](EmployeeID,Name,Address,Salary) VALUES('E004','Vikas Singh','Pune',300000)
Run the following query to verify the table data.
SELECT * FROM [dbo].[Employee]
All done with databse part. Now it’s time to work with the application part.
Open Visual Studio and create an MVC4 application:
Choose an empty template and create OK. An empty solution will be created.
If you will not choose an empty solution and you will get a default empty solution with HomeController.in the Controller Folder. By default Entity Framework is downloaded as a package in the application folder. If your application does not contain Entity Framework package you can download the Entity Framework package by just following the steps:
Goto Tools>Library Package Manager>Package Manager Console and install Entity Framework packages using the following Command.
Install-Package EntityFramework -Version 5.0.0
Add ADO.NET Entity Model to the Project:
Right Click on the Solution Explorer and select Add New Item to add ADO.NET Entity Model.
Enter EmployeeModel in name Textbox and Click on the Add button.
The next screen that will appear should look like this. Choose Generate From Database and click on the Next button.
Click on the New Connection button. The Next screen that will appear will look like this. Enter the values that are circled in the below snapshot and click on the OK button.
The next Screen Will look like this. Click on the Next button.
Check the Tables checkbox and click on the Finish button as in above snapshot.
Now we have done with the ADO.NET Entity Model part. The output window should look like this.
Right Click on the Controller folder and Create a Controller called EmployeeController
Type the name HomeCotroller in the Controller Name textbox. Select MVC controller with read/write actions and views, using Entity Framework From the Scaffolding Options, Select Employee. Select Employee Data Context class and click on the Add button as in below snapshot.
HomeController with the following code will be created.
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Web; using System.Web.Mvc; namespace EntityCRUDDemo.Controllers { public class HomeController : Controller { private EntityDemoEntities db = new EntityDemoEntities(); // // GET: /Home/ public ActionResult Index() { return View(db.Employees.ToList()); } // // GET: /Home/Details/5 public ActionResult Details(string id = null) { Employee employee = db.Employees.Find(id); if (employee == null) { return HttpNotFound(); } return View(employee); } // // GET: /Home/Create public ActionResult Create() { return View(); } // // POST: /Home/Create [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create(Employee employee) { if (ModelState.IsValid) { db.Employees.Add(employee); db.SaveChanges(); return RedirectToAction("Index"); } return View(employee); } // // GET: /Home/Edit/5 public ActionResult Edit(string id = null) { Employee employee = db.Employees.Find(id); if (employee == null) { return HttpNotFound(); } return View(employee); } // // POST: /Home/Edit/5 [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit(Employee employee) { if (ModelState.IsValid) { db.Entry(employee).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return View(employee); } // // GET: /Home/Delete/5 public ActionResult Delete(string id = null) { Employee employee = db.Employees.Find(id); if (employee == null) { return HttpNotFound(); } return View(employee); } // // POST: /Home/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(string id) { Employee employee = db.Employees.Find(id); db.Employees.Remove(employee); db.SaveChanges(); return RedirectToAction("Index"); } protected override void Dispose(bool disposing) { db.Dispose(); base.Dispose(disposing); } } }
You can see the following Views are created automatically in the Views folder.
If you see your View for creating Employee Record, you will not find an option for EmployeeID.
@model EntityCRUDDemo.Employee @{ ViewBag.Title = "Create"; } <h2>Create</h2> @using (Html.BeginForm()) { @Html.AntiForgeryToken() @Html.ValidationSummary(true) <fieldset> <legend>Employee</legend> <div class="editor-label"> @Html.LabelFor(model => model.Name) </div> <div class="editor-field"> @Html.EditorFor(model => model.Name) @Html.ValidationMessageFor(model => model.Name) </div> <div class="editor-label"> @Html.LabelFor(model => model.Address) </div> <div class="editor-field"> @Html.EditorFor(model => model.Address) @Html.ValidationMessageFor(model => model.Address) </div> <div class="editor-label"> @Html.LabelFor(model => model.Salary) </div> <div class="editor-field"> @Html.EditorFor(model => model.Salary) @Html.ValidationMessageFor(model => model.Salary) </div> <p> <input type="submit" value="Create" /> </p> </fieldset> } <div> @Html.ActionLink("Back to List", "Index") </div>
Replace your Create.cshtml file.
@model EntityCRUDDemo.Employee @{ ViewBag.Title = "Create"; } <h2>Create</h2> @using (Html.BeginForm()) { @Html.AntiForgeryToken() @Html.ValidationSummary(true) <fieldset> <legend>Employee</legend> <div class="editor-label"> @Html.LabelFor(model => model.EmployeeID) </div> <div class="editor-field"> @Html.EditorFor(model => model.EmployeeID) @Html.ValidationMessageFor(model => model.EmployeeID) </div> <div class="editor-label"> @Html.LabelFor(model => model.Name) </div> <div class="editor-field"> @Html.EditorFor(model => model.Name) @Html.ValidationMessageFor(model => model.Name) </div> <div class="editor-label"> @Html.LabelFor(model => model.Address) </div> <div class="editor-field"> @Html.EditorFor(model => model.Address) @Html.ValidationMessageFor(model => model.Address) </div> <div class="editor-label"> @Html.LabelFor(model => model.Salary) </div> <div class="editor-field"> @Html.EditorFor(model => model.Salary) @Html.ValidationMessageFor(model => model.Salary) </div> <p> <input type="submit" value="Create" /> </p> </fieldset> } <div> @Html.ActionLink("Back to List", "Index") </div>
Run the application and look at the output screen.
Index View:
Create View:
Edit View:
Details:
You can download the complete source code for the application from here.
Download the Database Script from here.
Hope you understand the CRUD operation using Entity Framework in ASP.NET.
View More:
Thank You.
dysfunction online pharmacy without scripts legit online pharmacy
canadian pharmacy generic viagra http://pharmacy-onlineasxs.com/ drug store news ce
pharmacy near me drugstore cowboy tops pharmacy
mens ed pills discount rx mens ed pills
best drugstore face wash canadian pharcharmy thrifty drug store
pharmacy cheap cheap erectile dysfunction pills online best drugstore foundation
Instagram takipçi satın almanın hesabınıza bir çok önemli katkısı bulunmaktadır. Instagram Türk gerçek takipçi satın al fırsatı ile şu avantajları elde edebilmeniz mümkün
canada pharmacy us online pharmacy express scripts pharmacy
I just could not depart your web site before suggesting that I extremely enjoyed the standard info a person provide for your visitors? Is going to be back often in order to check up on new posts
If some one desires to be updated with latest technologies therefore he must be pay a visit this website and be up to date all the time.|
Why viewers still make use of to read news papers when in this technological world all is accessible on net?|
Instagram takipçi hilesi 2021 özelliğini deneyebilirsiniz. Site adresinde en güvenilir takipçi paketleri bulunuyor.
Hey just wanted to give you a quick heads up and let you know a few of the images aren’t loading correctly. I’m not sure why but I think its a linking issue. I’ve tried it in two different browsers and both show the same results.
Instagram’ın ne kadar yaygın olarak kullanıldığı tartışılmayacak hale gelmiştir.