CRUD operation with Entity Framework 6 Database First using MVC 5 Scaffolding

Introduction

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

Scaffolding

Scaffolding is a technique to generate code for basic CRUD (create, read, update, and delete) operations against database. We can edit or customize this auto generated code according to our need.

Database First

We use Entity Framework designer which is in built feature of Visual Studio for automatically generate a data model with classes and properties of existing database tables and columns. The information about your database structure (store schema), your data model (conceptual model), and the mapping between them is stored in XML in an .edmx file. Entity Framework designer provides a graphical interface for display and edit the .edmx file.

Generate the models

We will use Entity Framework 6. We check the version of Entity Framework in the project if the version is less than 6 then use Manage NuGet Packages for, update version of Entity Framework.

cp9

Now we will create Entity Framework models from the database tables.

Step 1: Right-click the Models folder, and select Add and New Item.

cp10

Step 2: In the Add New Item window, select Data in the left pane and ADO.NET Entity Data Model from the center pane. Name the new model file OrgModel and Click Add.

cp11

Step 3: In the Entity Data Model Wizard, select Generate from database and Click Next.

cp12

Step 4: Click the New Connection button.

cp13

Step 5: In the Connection Properties window, provide the name of the local server where database was created (in this case (localdb)\Projects). After providing the server name, select the OrganizationEmployee from the available databases then click ok.

cp14

Step 6: You can use the default name for connection for save in the Web.Config file and click next.

cp15

Step 7: Select Tables to generate models for all three tables and click finish.

cp16

The Models folder now includes many new files related to the models that were generated from the database.

cp17

The OrgModel.Context.cs file contains a class that derives from the DbContext class, and provides a property for each model class that corresponds to a database table. The Department.cs, Enrollment.cs, and Employee.cs files contain the model classes that represent the databases tables. You will use both the context class and the model classes when working with scaffolding.
Before proceeding with this tutorial, build the project. In the next section, you will generate code based on the data models, but that section will not work if the project has not been built.

Add scaffold

Step 1: Add the new controller to the existing Controllers folder. Right-click the Controllers folder, and select Add – New Scaffolded Item.

cp18

Step 2: Select the MVC 5 Controller with views, using Entity Framework option. This option will generate the controller and views for updating, deleting, creating and displaying the data in your model.

cp19

Step 3: Add the controller name as EmployeeController then select Employee for the model class, and select the OrganizationEmployeeEntities for the context class now click add.

cp20

If you receive an error, it may be because you did not build the project in the previous section. If so, try building the project, and then add the scaffolded item again.
After the code generation process is complete, you will see a new controller and views in your project.
Perform the same steps again, but add a scaffold for the Enrollment class. When finished, you should have an EnrollmentsController.cs file, and a folder under Views named Enrollments with the Create, Delete, Details, Edit and Index views.

cp21

Step 4: We see our employee 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.Net;
using System.Web;
using System.Web.Mvc;
using OrganizationDetails.Models;

namespace OrganizationDetails.Controllers
{
    public class EmployeeController : Controller
    {
        private OrganizationEmployeeEntities db = new OrganizationEmployeeEntities();

        // GET: /Employee/
        public ActionResult Index()
        {
            return View(db.Employees.ToList());
        }

        // GET: /Employee/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Employee employee = db.Employees.Find(id);
            if (employee == null)
            {
                return HttpNotFound();
            }
            return View(employee);
        }

        // GET: /Employee/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: /Employee/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "EmployeeID,LastName,FirstName,JoiningDate")] Employee employee)
        {
            if (ModelState.IsValid)
            {
                db.Employees.Add(employee);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(employee);
        }

        // GET: /Employee/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Employee employee = db.Employees.Find(id);
            if (employee == null)
            {
                return HttpNotFound();
            }
            return View(employee);
        }

        // POST: /Employee/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "EmployeeID,LastName,FirstName,JoiningDate")] Employee employee)
        {
            if (ModelState.IsValid)
            {
                db.Entry(employee).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(employee);
        }

        // GET: /Employee/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Employee employee = db.Employees.Find(id);
            if (employee == null)
            {
                return HttpNotFound();
            }
            return View(employee);
        }

        // POST: /Employee/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Employee employee = db.Employees.Find(id);
            db.Employees.Remove(employee);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}

Add links to new views

To make it easier for you to navigate to your new views, you can add a couple of hyperlinks to the Index views for students and enrollments. Open the file at Views/Home/Index.cshtml, which is the home page for your site. Add the following code.

<div>
    @Html.ActionLink("List of employee", "Index", "Employee")<br />
    @Html.ActionLink("List of enrollments", "Index", "Enrollment")
</div>

Conclusion

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

One thought on “CRUD operation with Entity Framework 6 Database First using MVC 5 Scaffolding

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>