01 August 2016 Sudhanshu Ranjan 1.06k

Code first approach with CRUD operation in MVC Application

In last article I have shown datepicker textbox in mvc 4 using JQuery, Bind dropdown in MVC using jquery with C#. Now today I am going to show how to work with code first approach using Entity Framework and how to perform CRUD operation in MVC application. In code first approach we transform our coded classes into a database design.

Follow the Steps to implement CRUD operation using Code First approach.

Step 1: Create a Context class and derived it from DbContext class. Expose DbSet properties to define the model classes which will create table after migration.
Add namespace  System.Data.Entity for DbContext class

Step 2: Create Employee Model Class

Step 3: Open Package Console Manager and run the migration. Once it will run successfully you will see, database has been created.

Step 4: Create Employee Controller with action and its Views.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CodeFirstInMVC.Models;
using System.Data;

namespace CodeFirstInMVC.Controllers
{
    public class EmployeeController : Controller
    {
        DatabaseContext db = new DatabaseContext();
        //
        // GET: /Employee/

        public ActionResult Index()
        {
            var data = db.Employees.OrderByDescending(x => x.Id).ToList();
            return View(data);
        }

        public ActionResult Add()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Add(Employee model)
        {
            if (ModelState.IsValid)
            {
                db.Employees.Add(model);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            else
            {
                return View(model);
            }
        }

        public ActionResult Edit(int id)
        {
            Employee model = db.Employees.Where(x => x.Id == id).FirstOrDefault();
            return View(model);
        }

        [HttpPost]
        public ActionResult Edit(Employee model)
        {
            db.Entry(model).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        public ActionResult Delete(int id)
        {
            Employee model = db.Employees.Where(x => x.Id == id).FirstOrDefault();
            if (model != null)
            {
                db.Employees.Remove(model);
                db.SaveChanges();
            }
            return RedirectToAction("Index");
        }
    }
}

Step 5: Index.cshtml Views

@model IEnumerable<CodeFirstInMVC.Models.Employee>
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>View Employee List </h2>
<p>
    <b>
        @Html.ActionLink("Add New Employee", "Add", "Employee")
    </b>
</p>
<div>
    @foreach (var item in Model)
    {
        <div>Employee Id : @item.Id</div>
        <div>Employee Name : @item.EmployeeName</div>
        <div>Address : @item.Address</div>
        <div>Email Id : @item.EmailId</div>
        <div>Phone : @item.PhoneNumber</div>
        <div><b>@Html.ActionLink("Edit", "Edit", "Employee", new { @id = item.Id }, null) | @Html.ActionLink("Delete", "Delete", "Employee", new { @id = item.Id }, null)</b></div>
        <hr />
    }
</div>

Step 6: Add.cshtml Views

@model CodeFirstInMVC.Models.Employee
@{
    ViewBag.Title = "Add";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Add</h2>

@using (Html.BeginForm())
{
    <div>
        @Html.LabelFor(m => m.EmployeeName)
        @Html.EditorFor(m => m.EmployeeName)
    </div>

    <div>
        @Html.LabelFor(m => m.Address)
        @Html.EditorFor(m => m.Address)
    </div>

    <div>
        @Html.LabelFor(m => m.EmailId)
        @Html.EditorFor(m => m.EmailId)
    </div>

    <div>
        @Html.LabelFor(m => m.PhoneNumber)
        @Html.EditorFor(m => m.PhoneNumber)
    </div>

    <div>
        @Html.LabelFor(m => m.RegistrationDate)
        @Html.EditorFor(m => m.RegistrationDate)
    </div>

    <div>
        @Html.LabelFor(m => m.IsActive)
        @Html.EditorFor(m => m.IsActive)
    </div>

    <div>
        <input type="submit" name="submit" value="Submit" />
    </div>
}

Step 7: Edit.cshtml Views

@model CodeFirstInMVC.Models.Employee
@{
    ViewBag.Title = "Edit";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Edit</h2>

@using (Html.BeginForm())
{
    <div>
        @Html.LabelFor(m => m.EmployeeName)
        @Html.EditorFor(m => m.EmployeeName)
    </div>

    <div>
        @Html.LabelFor(m => m.Address)
        @Html.EditorFor(m => m.Address)
    </div>

    <div>
        @Html.LabelFor(m => m.EmailId)
        @Html.EditorFor(m => m.EmailId)
    </div>

    <div>
        @Html.LabelFor(m => m.PhoneNumber)
        @Html.EditorFor(m => m.PhoneNumber)
    </div>

    <div>
        @Html.LabelFor(m => m.RegistrationDate)
        @Html.EditorFor(m => m.RegistrationDate)
    </div>

    <div>
        @Html.LabelFor(m => m.IsActive)
        @Html.EditorFor(m => m.IsActive)
        @Html.HiddenFor(m => m.Id)
    </div>

    <div>
        <input type="submit" name="submit" value="Submit" />
    </div>
}

 

Please download the sample project.

 

Now if you want to add more table then you should follow the same. Create Model class and add migration. Suppose you have Customer Model class.

If you want to revert back the migration.

Please feel free to ask any doubt here!!

You can share at :

About Author
Sudhanshu Kumar Ranjan | Lead Engineer at HCL Technologies | Expertise in Microsoft Technology | Author | Blogger | Programmer
Know More
Connect with him on Facebook | Google+ | LinkedIn | Twitter

Recommended Post

Leave a comment

About Dotnet Cube

It's my blog - Dotnet Cube, where you will learn and get solutions about programming, web designing and development. I started this website to share my knowledge and experience which might help someone.

You can get more details about me and my blog at About Us page.

Subscribe Newsletter

Subscribe to our monthly newsletter to get the latest industry news, Media Group updates and our current specials.

Follow On Us...

Home | About | Advertise | Copyrights | Privacy | Contact | Admin

Copyrights © 2015-2017 dotnetcube.com. All rights reserved