| by Achyut Kendre | No comments

Curd Operations using Entity Framework Code First and ASP.NET MVC

ASP NET MVC 5

Example Code: –https://drive.google.com/file/d/1G5oroBmfsy30_avDAlZrsy27KGPCBGRl/view?usp=sharing

You can do the curd operations as we do it using DbFirst their is no change in it.

Step 1: Index Action Code

 CompanyContext cc = new CompanyContext();
        public ActionResult Index()
        {
            return View(cc.Emps.ToList());
        }

Index View Code with Index.cshtml

@model IEnumerable<CodeFirstEx.Models.Emp>

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <p>
        @Html.ActionLink("Create New", "Create")
    </p>
    <table class="table">
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.EmpDept.DeptName)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.EmpName)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Address)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.EmailID)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.MobileNo)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Salary)
            </th>
            <th></th>
        </tr>
    
    @foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.EmpDept.DeptName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.EmpName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Address)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.EmailID)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.MobileNo)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Salary)
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { id=item.EmpID }) |
                @Html.ActionLink("Details", "Details", new { id=item.EmpID }) |
                @Html.ActionLink("Delete", "Delete", new { id=item.EmpID })
            </td>
        </tr>
    }
    
    </table>
</body>
</html>

Step 2 : to create the Emp we need to create the create action with HttpGet and HttpPost as follows –

 [HttpGet]
        public ActionResult Create()
        {
            ViewBag.DeptID = new SelectList(cc.Depts.ToList(), "DeptID", "DeptName");
            return View();
        }


        [HttpPost]
        public ActionResult Create(Emp rec)
        {
            cc.Emps.Add(rec);
            cc.SaveChanges();
            return RedirectToAction("Index");
        }

Step 3: You can do the Edit of employee, create following two edit actions with HttpGet and HttpPost.

[HttpGet]
public ActionResult Edit(Int64 id)
{
 var rec = cc.Emps.Find(id);
 ViewBag.DeptID = new SelectList(cc.Depts.ToList(), "DeptID", "DeptName",rec.DeptID);
 return View(rec);
}
[HttpPost]
public ActionResult Edit(Emp rec)
{
 ViewBag.DeptID = new SelectList(cc.Depts.ToList(), "DeptID", "DeptName", rec.DeptID);
   if (ModelState.IsValid)    {
    cc.Entry(rec).State = System.Data.Entity.EntityState.Modified;
    cc.SaveChanges();
    return RedirectToAction("Index");
}
   return View(rec);
}

Edit View Code: –

@model CodeFirstEx1.Models.Emp

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Edit</title>
</head>
<body>
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/jqueryval")
    
    
    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
        
        <div class="form-horizontal">
            <h4>Emp</h4>
            <hr />
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            @Html.HiddenFor(model => model.EmpID)
    
            <div class="form-group">
                @Html.LabelFor(model => model.EmpName, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.EmpName, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.EmpName, "", new { @class = "text-danger" })
                </div>
            </div>
    
            <div class="form-group">
                @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })
                </div>
            </div>
    
            <div class="form-group">
                @Html.LabelFor(model => model.EmailID, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.EmailID, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.EmailID, "", new { @class = "text-danger" })
                </div>
            </div>
    
            <div class="form-group">
                @Html.LabelFor(model => model.MobileNo, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.MobileNo, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.MobileNo, "", new { @class = "text-danger" })
                </div>
            </div>
    
            <div class="form-group">
                @Html.LabelFor(model => model.Salary, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Salary, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.Salary, "", new { @class = "text-danger" })
                </div>
            </div>
    
            <div class="form-group">
                @Html.LabelFor(model => model.DeptID, "DeptID", htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.DropDownList("DeptID", null, htmlAttributes: new { @class = "form-control" })
                    @Html.ValidationMessageFor(model => model.DeptID, "", new { @class = "text-danger" })
                </div>
            </div>
    
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Save" class="btn btn-default" />
                </div>
            </div>
        </div>
    }
    
    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>
</body>
</html>

Step 4: You can delete the record by showing the record to the user and delete it as follows –

Delete action code as follows –

 [HttpGet]
 public ActionResult Delete(Int64 id)
 {
  var rec = cc.Emps.Find(id);
 return View(rec);
 }
[HttpPost]
[ActionName("Delete")]
public ActionResult DeleteEmp(Int64 id)
  {
     var rec = cc.Emps.Find(id);
     cc.Emps.Remove(rec);
     cc.SaveChanges();
     return RedirectToAction("Index");
   }

Delete view code Delete.cshtml

[HttpGet]
 public ActionResult Delete(Int64 id)
 {
   var rec = cc.Emps.Find(id);
   return View(rec);
  }

[HttpPost]
[ActionName("Delete")]
public ActionResult DeleteEmp(Int64 id)
{
   var rec = cc.Emps.Find(id);
   cc.Emps.Remove(rec);
   cc.SaveChanges();
   return RedirectToAction("Index");
}