MVC 5 With Entity Framework: Basic CRUD Operations With Visual Studio 2013

Look at the following image:

soluction explorer

MVC Project Prerequeste:

  • Create a MVC4/5 project in VB 2010/2012/2013.
  • Add an Entity Framework 5/6.

Create MVC5 Project

  • Create a new "ASP.NET Web Application" project.
  • Name it MVCEFDM.
  • Provide a Project Location in Local Host/Disk Drive and click Ok.
  • Select the MVC From Project Option.

It will create a new MVC5 project with Entity Framework 5/6 already installed, if it is not installed then install it from the nuGet Repository from: NuGet.

Database design

  • Create a database for performing CRUD operations on only one table.
  • The schema of the Employee table is as below.

Create Data Model

  1. Right-click on the Model and select "Add | New Item..." .

  2. From the Data tab select ADO.Net Entity Data Model.

  3. Provide the name of the EntityModel as “EmployeeModel” and click the Add button.

  4. You will get a dialog box. From there select the "Generate from database" option.

  5. Create a new connection that includes the senstive data in it / or Not option.

  6. ByDefault It will create a database name as in the following logic.

    Database name + Entities = default connection setting name

  7. Open Web.config to see the connection string and see that it will create a new connection string with the information as:

    name: name of connection string for entity dbStudentEntities.

    meta data with

    Models.EmployeeModel.csdl|res://*/Models.EmployeeModel.ssdl|res://*/Models.EmployeeModel.msl;

    Data Sources:
    Terminal10
    initial catalog: dbStudent

    And App=EntityFramework"" providerName="System.Data.EntityClient" and so on.

  8. The complete Connection String is:
    1. <add name="dbStudentEntities" connectionString="metadata=res://*/Models.EmployeeModel.csdl|res://*/Models.EmployeeModel.ssdl|res://*/Models.EmployeeModel.msl;provider=System.Data.SqlClient;provider connection string="data source=Terminal10;initial catalog=dbStudent;user id=sa;password=sa;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />  
  9. Now you need to choose the data objects to make them a part of the Data Model. From the dialog box you can choose tables, Stored Procedures and views.

    Select Employee table to perfrom CRUD operations only on this.

    The Model namespace name by default would be the database name suffixed with Model.

    Now click Finish to create the data model as EmployeeModel.edmx.

  10. Create a Layout.cshtml page in the View/Shared folder.
    1. <!DOCTYPE html>  
    2. <html>  
    3. <head>  
    4.     <meta charset="utf-8" />  
    5.     <meta name="viewport" content="width=device-width" />  
    6.     <title>@ViewBag.Title</title>  
    7.     @Styles.Render("~/Content/css")  
    8.     @Scripts.Render("~/bundles/modernizr")  
    9. </head>  
    10. <body>  
    11.     @RenderBody()  
    12.   
    13.     @Scripts.Render("~/bundles/jquery")  
    14.     @RenderSection("scripts", required: false)  
    15. </body>  
    16. </html>  
    Error.cshtml
    1. @{  
    2.     Layout = null;  
    3. }  
    4.   
    5. <!DOCTYPE html>  
    6. <html>  
    7. <head>  
    8.     <meta name="viewport" content="width=device-width" />  
    9.     <title>Error</title>  
    10. </head>  
    11. <body>  
    12.     <hgroup>  
    13.         <h1>Error.</h1>  
    14.         <h2>An error occurred while processing your request.</h2>  
    15.     </hgroup>  
    16. </body>  
    17. </html>  
    _ViewStart.cshtml
    1. @{  
    2. Layout = "~/Views/Shared/_Layout.cshtml";  
    3. }  

Performing CRUD operation

[Model] : EmployeeModel

It consists of the 2 main Files EmployeeModel.Context.tt and EmployeeModel.tt.

In EmployeeModel.Context.tt – It consists of EmployeeModel.Context.cs

EmployeeModel.Context.cs:

It consists of a dbStudentEntities class for the connection string context.

  1. namespace MVCEFDM.Models  
  2. {  
  3.     using System;  
  4.     using System.Data.Entity;  
  5.     using System.Data.Entity.Infrastructure;  
  6.       
  7.     public partial class dbStudentEntities : DbContext  
  8.     {  
  9.         public dbStudentEntities() : base("name=dbStudentEntities")  
  10.         {  
  11.         }  
  12.       
  13.         protected override void OnModelCreating(DbModelBuilder modelBuilder)  
  14.         {  
  15.             throw new UnintentionalCodeFirstException();  
  16.         }  
  17.       
  18.         public DbSet<Employee> Employees { getset; }  
  19.     }  
  20. }  
In EmployeeModel.tt – It consists of Employee.cs and EmployeeModel.cs

Employee.cs : Employee Model
  1. namespace MVCEFDM.Models  
  2. {  
  3.     using System;  
  4.     using System.Collections.Generic;  
  5.       
  6.     public partial class Employee  
  7.     {  
  8.         public int Id { getset; }  
  9.         public string Id1 { getset; }  
  10.         public string Name { getset; }  
  11.         public string desig { getset; }  
  12.         public string salary { getset; }  
  13.     }  
  14. }  

Creating Controller

Step 1

Right-click on the Controller, Select Controller. It will open an Add Scaffold window.

Step 2

Select MVC5 Controller with views, using Entity Framework.

controller

add controller

Step 3

It will automatically create a Controller with all the necessary operations.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Data;  
  4. using System.Data.Entity;  
  5. using System.Linq;  
  6. using System.Net;  
  7. using System.Web;  
  8. using System.Web.Mvc;  
  9. using MVCEFDM.Models;  
  10.   
  11. namespace MVCEFDM.Controllers  
  12. {  
  13.     public class EmployeesController : Controller  
  14.     {  
  15.         private dbStudentEntities db = new dbStudentEntities();  
  16.   
  17.         // GET: Employees  
  18.         public ActionResult Index()  
  19.         {  
  20.             return View(db.Employees.ToList());  
  21.         }  
  22.   
  23.         // GET: Employees/Details/5  
  24.         public ActionResult Details(int? id)  
  25.         {  
  26.             if (id == null)  
  27.             {  
  28.                 return new HttpStatusCodeResult(HttpStatusCode.BadRequest);  
  29.             }  
  30.             Employee employee = db.Employees.Find(id);  
  31.             if (employee == null)  
  32.             {  
  33.                 return HttpNotFound();  
  34.             }  
  35.             return View(employee);  
  36.         }  
  37.   
  38.         // GET: Employees/Create  
  39.         public ActionResult Create()  
  40.         {  
  41.             return View();  
  42.         }  
  43.   
  44.         // POST: Employees/Create  
  45.         // To protect from overposting attacks, please enable the specific properties you want to bind to, for   
  46.         // more details see http://go.microsoft.com/fwlink/?LinkId=317598.  
  47.         [HttpPost]  
  48.         [ValidateAntiForgeryToken]  
  49.         public ActionResult Create([Bind(Include = "Id,Id1,Name,desig,salary")] Employee employee)  
  50.         {  
  51.             if (ModelState.IsValid)  
  52.             {  
  53.                 db.Employees.Add(employee);  
  54.                 db.SaveChanges();  
  55.                 return RedirectToAction("Index");  
  56.             }  
  57.   
  58.             return View(employee);  
  59.         }  
  60.   
  61.         // GET: Employees/Edit/5  
  62.         public ActionResult Edit(int? id)  
  63.         {  
  64.             if (id == null)  
  65.             {  
  66.                 return new HttpStatusCodeResult(HttpStatusCode.BadRequest);  
  67.             }  
  68.             Employee employee = db.Employees.Find(id);  
  69.             if (employee == null)  
  70.             {  
  71.                 return HttpNotFound();  
  72.             }  
  73.             return View(employee);  
  74.         }  
  75.   
  76.         // POST: Employees/Edit/5  
  77.         // To protect from overposting attacks, please enable the specific properties you want to bind to, for   
  78.         // more details see http://go.microsoft.com/fwlink/?LinkId=317598.  
  79.         [HttpPost]  
  80.         [ValidateAntiForgeryToken]  
  81.         public ActionResult Edit([Bind(Include = "Id,Id1,Name,desig,salary")] Employee employee)  
  82.         {  
  83.             if (ModelState.IsValid)  
  84.             {  
  85.                 db.Entry(employee).State = EntityState.Modified;  
  86.                 db.SaveChanges();  
  87.                 return RedirectToAction("Index");  
  88.             }  
  89.             return View(employee);  
  90.         }  
  91.   
  92.         // GET: Employees/Delete/5  
  93.         public ActionResult Delete(int? id)  
  94.         {  
  95.             if (id == null)  
  96.             {  
  97.                 return new HttpStatusCodeResult(HttpStatusCode.BadRequest);  
  98.             }  
  99.             Employee employee = db.Employees.Find(id);  
  100.             if (employee == null)  
  101.             {  
  102.                 return HttpNotFound();  
  103.             }  
  104.             return View(employee);  
  105.         }  
  106.   
  107.         // POST: Employees/Delete/5  
  108.         [HttpPost, ActionName("Delete")]  
  109.         [ValidateAntiForgeryToken]  
  110.         public ActionResult DeleteConfirmed(int id)  
  111.         {  
  112.             Employee employee = db.Employees.Find(id);  
  113.             db.Employees.Remove(employee);  
  114.             db.SaveChanges();  
  115.             return RedirectToAction("Index");  
  116.         }  
  117.   
  118.         protected override void Dispose(bool disposing)  
  119.         {  
  120.             if (disposing)  
  121.             {  
  122.                 db.Dispose();  
  123.             }  
  124.             base.Dispose(disposing);  
  125.         }  
  126.     }  
  127. }  

Step 4

It will automatically create a View for performing CRUD operations.

Create.cshtml

  1. @model MVCEFDM.Models.Employee  
  2.   
  3. @{  
  4.     ViewBag.Title = "Create";  
  5.     Layout = "~/Views/Shared/_Layout.cshtml";  
  6. }  
  7.   
  8. <h2>Create</h2>  
  9.   
  10.   
  11. @using (Html.BeginForm())   
  12. {  
  13.     @Html.AntiForgeryToken()  
  14.       
  15.     <div class="form-horizontal">  
  16.         <h4>Employee</h4>  
  17.         <hr />  
  18.         @Html.ValidationSummary(true""new { @class = "text-danger" })  
  19.         <div class="form-group">  
  20.             @Html.LabelFor(model => model.Id, htmlAttributes: new { @class = "control-label col-md-2" })  
  21.             <div class="col-md-10">  
  22.                 @Html.EditorFor(model => model.Id, new { htmlAttributes = new { @class = "form-control" } })  
  23.                 @Html.ValidationMessageFor(model => model.Id, ""new { @class = "text-danger" })  
  24.             </div>  
  25.         </div>  
  26.   
  27.         <div class="form-group">  
  28.             @Html.LabelFor(model => model.Id1, htmlAttributes: new { @class = "control-label col-md-2" })  
  29.             <div class="col-md-10">  
  30.                 @Html.EditorFor(model => model.Id1, new { htmlAttributes = new { @class = "form-control" } })  
  31.                 @Html.ValidationMessageFor(model => model.Id1, ""new { @class = "text-danger" })  
  32.             </div>  
  33.         </div>  
  34.   
  35.         <div class="form-group">  
  36.             @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })  
  37.             <div class="col-md-10">  
  38.                 @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })  
  39.                 @Html.ValidationMessageFor(model => model.Name, ""new { @class = "text-danger" })  
  40.             </div>  
  41.         </div>  
  42.   
  43.         <div class="form-group">  
  44.             @Html.LabelFor(model => model.desig, htmlAttributes: new { @class = "control-label col-md-2" })  
  45.             <div class="col-md-10">  
  46.                 @Html.EditorFor(model => model.desig, new { htmlAttributes = new { @class = "form-control" } })  
  47.                 @Html.ValidationMessageFor(model => model.desig, ""new { @class = "text-danger" })  
  48.             </div>  
  49.         </div>  
  50.   
  51.         <div class="form-group">  
  52.             @Html.LabelFor(model => model.salary, htmlAttributes: new { @class = "control-label col-md-2" })  
  53.             <div class="col-md-10">  
  54.                 @Html.EditorFor(model => model.salary, new { htmlAttributes = new { @class = "form-control" } })  
  55.                 @Html.ValidationMessageFor(model => model.salary, ""new { @class = "text-danger" })  
  56.             </div>  
  57.         </div>  
  58.   
  59.         <div class="form-group">  
  60.             <div class="col-md-offset-2 col-md-10">  
  61.                 <input type="submit" value="Create" class="btn btn-default" />  
  62.             </div>  
  63.         </div>  
  64.     </div>  
  65. }  
  66.   
  67. <div>  
  68.     @Html.ActionLink("Back to List""Index")  
  69. </div>  
  70.   
  71. @section Scripts {  
  72.     @Scripts.Render("~/bundles/jqueryval")  
  73. }  
Delete.cshtml
  1. @model MVCEFDM.Models.Employee  
  2.   
  3. @{  
  4.     ViewBag.Title = "Delete";  
  5.     Layout = "~/Views/Shared/_Layout.cshtml";  
  6. }  
  7.   
  8. <h2>Delete</h2>  
  9.   
  10. <h3>Are you sure you want to delete this?</h3>  
  11. <div>  
  12.     <h4>Employee</h4>  
  13.     <hr />  
  14.     <dl class="dl-horizontal">  
  15.         <dt>  
  16.             @Html.DisplayNameFor(model => model.Id1)  
  17.         </dt>  
  18.   
  19.         <dd>  
  20.             @Html.DisplayFor(model => model.Id1)  
  21.         </dd>  
  22.   
  23.         <dt>  
  24.             @Html.DisplayNameFor(model => model.Name)  
  25.         </dt>  
  26.   
  27.         <dd>  
  28.             @Html.DisplayFor(model => model.Name)  
  29.         </dd>  
  30.   
  31.         <dt>  
  32.             @Html.DisplayNameFor(model => model.desig)  
  33.         </dt>  
  34.   
  35.         <dd>  
  36.             @Html.DisplayFor(model => model.desig)  
  37.         </dd>  
  38.   
  39.         <dt>  
  40.             @Html.DisplayNameFor(model => model.salary)  
  41.         </dt>  
  42.   
  43.         <dd>  
  44.             @Html.DisplayFor(model => model.salary)  
  45.         </dd>  
  46.   
  47.     </dl>  
  48.   
  49.     @using (Html.BeginForm()) {  
  50.         @Html.AntiForgeryToken()  
  51.   
  52.         <div class="form-actions no-color">  
  53.             <input type="submit" value="Delete" class="btn btn-default" /> |  
  54.             @Html.ActionLink("Back to List""Index")  
  55.         </div>  
  56.     }  
  57. </div>  
Details.cshtml

@model MVCEFDM.Models.Employee
  1.   
  2. @{  
  3.     ViewBag.Title = "Details";  
  4.     Layout = "~/Views/Shared/_Layout.cshtml";  
  5. }  
  6.   
  7. <h2>Details</h2>  
  8.   
  9. <div>  
  10.     <h4>Employee</h4>  
  11.     <hr />  
  12.     <dl class="dl-horizontal">  
  13.         <dt>  
  14.             @Html.DisplayNameFor(model => model.Id1)  
  15.         </dt>  
  16.   
  17.         <dd>  
  18.             @Html.DisplayFor(model => model.Id1)  
  19.         </dd>  
  20.   
  21.         <dt>  
  22.             @Html.DisplayNameFor(model => model.Name)  
  23.         </dt>  
  24.   
  25.         <dd>  
  26.             @Html.DisplayFor(model => model.Name)  
  27.         </dd>  
  28.   
  29.         <dt>  
  30.             @Html.DisplayNameFor(model => model.desig)  
  31.         </dt>  
  32.   
  33.         <dd>  
  34.             @Html.DisplayFor(model => model.desig)  
  35.         </dd>  
  36.   
  37.         <dt>  
  38.             @Html.DisplayNameFor(model => model.salary)  
  39.         </dt>  
  40.   
  41.         <dd>  
  42.             @Html.DisplayFor(model => model.salary)  
  43.         </dd>  
  44.   
  45.     </dl>  
  46. </div>  
  47. <p>  
  48.     @Html.ActionLink("Edit""Edit"new { id = Model.Id }) |  
  49.     @Html.ActionLink("Back to List""Index")  
  50. </p>  
Edit.cshtml
  1. @model MVCEFDM.Models.Employee  
  2.   
  3. @{  
  4.     ViewBag.Title = "Edit";  
  5.     Layout = "~/Views/Shared/_Layout.cshtml";  
  6. }  
  7.   
  8. <h2>Edit</h2>  
  9.   
  10.   
  11. @using (Html.BeginForm())  
  12. {  
  13.     @Html.AntiForgeryToken()  
  14.       
  15.     <div class="form-horizontal">  
  16.         <h4>Employee</h4>  
  17.         <hr />  
  18.         @Html.ValidationSummary(true""new { @class = "text-danger" })  
  19.         @Html.HiddenFor(model => model.Id)  
  20.   
  21.         <div class="form-group">  
  22.             @Html.LabelFor(model => model.Id1, htmlAttributes: new { @class = "control-label col-md-2" })  
  23.             <div class="col-md-10">  
  24.                 @Html.EditorFor(model => model.Id1, new { htmlAttributes = new { @class = "form-control" } })  
  25.                 @Html.ValidationMessageFor(model => model.Id1, ""new { @class = "text-danger" })  
  26.             </div>  
  27.         </div>  
  28.   
  29.         <div class="form-group">  
  30.             @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })  
  31.             <div class="col-md-10">  
  32.                 @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })  
  33.                 @Html.ValidationMessageFor(model => model.Name, ""new { @class = "text-danger" })  
  34.             </div>  
  35.         </div>  
  36.   
  37.         <div class="form-group">  
  38.             @Html.LabelFor(model => model.desig, htmlAttributes: new { @class = "control-label col-md-2" })  
  39.             <div class="col-md-10">  
  40.                 @Html.EditorFor(model => model.desig, new { htmlAttributes = new { @class = "form-control" } })  
  41.                 @Html.ValidationMessageFor(model => model.desig, ""new { @class = "text-danger" })  
  42.             </div>  
  43.         </div>  
  44.   
  45.         <div class="form-group">  
  46.             @Html.LabelFor(model => model.salary, htmlAttributes: new { @class = "control-label col-md-2" })  
  47.             <div class="col-md-10">  
  48.                 @Html.EditorFor(model => model.salary, new { htmlAttributes = new { @class = "form-control" } })  
  49.                 @Html.ValidationMessageFor(model => model.salary, ""new { @class = "text-danger" })  
  50.             </div>  
  51.         </div>  
  52.   
  53.         <div class="form-group">  
  54.             <div class="col-md-offset-2 col-md-10">  
  55.                 <input type="submit" value="Save" class="btn btn-default" />  
  56.             </div>  
  57.         </div>  
  58.     </div>  
  59. }  
  60.   
  61. <div>  
  62.     @Html.ActionLink("Back to List""Index")  
  63. </div>  
  64.   
  65. @section Scripts {  
  66.     @Scripts.Render("~/bundles/jqueryval")  
  67. }  
Index.cshtml
  1. @model IEnumerable<MVCEFDM.Models.Employee>  
  2.   
  3. @{  
  4.     ViewBag.Title = "Index";  
  5.     Layout = "~/Views/Shared/_Layout.cshtml";  
  6. }  
  7.   
  8. <h2>Index</h2>  
  9.   
  10. <p>  
  11.     @Html.ActionLink("Create New""Create")  
  12. </p>  
  13. <table class="table">  
  14.     <tr>  
  15.         <th>  
  16.             @Html.DisplayNameFor(model => model.Id1)  
  17.         </th>  
  18.         <th>  
  19.             @Html.DisplayNameFor(model => model.Name)  
  20.         </th>  
  21.         <th>  
  22.             @Html.DisplayNameFor(model => model.desig)  
  23.         </th>  
  24.         <th>  
  25.             @Html.DisplayNameFor(model => model.salary)  
  26.         </th>  
  27.         <th></th>  
  28.     </tr>  
  29.   
  30. @foreach (var item in Model) {  
  31.     <tr>  
  32.         <td>  
  33.             @Html.DisplayFor(modelItem => item.Id1)  
  34.         </td>  
  35.         <td>  
  36.             @Html.DisplayFor(modelItem => item.Name)  
  37.         </td>  
  38.         <td>  
  39.             @Html.DisplayFor(modelItem => item.desig)  
  40.         </td>  
  41.         <td>  
  42.             @Html.DisplayFor(modelItem => item.salary)  
  43.         </td>  
  44.         <td>  
  45.             @Html.ActionLink("Edit""Edit"new { id=item.Id }) |  
  46.             @Html.ActionLink("Details""Details"new { id=item.Id }) |  
  47.             @Html.ActionLink("Delete""Delete"new { id=item.Id })  
  48.         </td>  
  49.     </tr>  
  50. }  
  51.   
  52. </table>  
The output will be:

create index

 


Similar Articles