Working With Entity Framework 6.0 in MVC (Basic CRUD Operations) : Part 2

In the previous tutorial we created an MVC application that displays data using the Entity Framework and SQL Server Database. In this tutorial we will customize the Create, Update and Delete (CRUD) code using Entity Framework.

For this, we customized the Index Page of the previous article. In the table structure where we display the data, add a new column to add two new link buttons for it.

 

Also, we add a <p> tag above the <table> tag and provide the following code:

 
 
Now the Create New link button will be used to create new records for a customer and save into the database. For doing that, we first add an action to the controller as below:
  1. public ActionResult Create()  
  2.       {  
  3.           return View();  
  4.       }  
As shown is the preceding code, this actionresult will be redirected to a new view named "Create". For this, we add a view to the Customer Folder and provide the following code within it:
  1. @model EFRndProject.Models.Customer  
  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>Customer</h4>  
  17.         <hr />  
  18.         @Html.ValidationSummary(true)  
  19.   
  20.         <div class="form-group">  
  21.             @Html.LabelFor(model => model.CustomerName, new { @class = "control-label col-md-2" })  
  22.             <div class="col-md-10">  
  23.                 @Html.EditorFor(model => model.CustomerName)  
  24.                 @Html.ValidationMessageFor(model => model.CustomerName)  
  25.             </div>  
  26.         </div>  
  27.   
  28.         <div class="form-group">  
  29.             @Html.LabelFor(model => model.CustAddress, new { @class = "control-label col-md-2" })  
  30.             <div class="col-md-10">  
  31.                 @Html.EditorFor(model => model.CustAddress)  
  32.                 @Html.ValidationMessageFor(model => model.CustAddress)  
  33.             </div>  
  34.         </div>  
  35.   
  36.         <div class="form-group">  
  37.             @Html.LabelFor(model => model.CustCity, new { @class = "control-label col-md-2" })  
  38.             <div class="col-md-10">  
  39.                 @Html.EditorFor(model => model.CustCity)  
  40.                 @Html.ValidationMessageFor(model => model.CustCity)  
  41.             </div>  
  42.         </div>  
  43.   
  44.         <div class="form-group">  
  45.             @Html.LabelFor(model => model.CustPinCode, new { @class = "control-label col-md-2" })  
  46.             <div class="col-md-10">  
  47.                 @Html.EditorFor(model => model.CustPinCode)  
  48.                 @Html.ValidationMessageFor(model => model.CustPinCode)  
  49.             </div>  
  50.         </div>  
  51.   
  52.         <div class="form-group">  
  53.             @Html.LabelFor(model => model.PhoneNo, new { @class = "control-label col-md-2" })  
  54.             <div class="col-md-10">  
  55.                 @Html.EditorFor(model => model.PhoneNo)  
  56.                 @Html.ValidationMessageFor(model => model.PhoneNo)  
  57.             </div>  
  58.         </div>  
  59.   
  60.         <div class="form-group">  
  61.             <div class="col-md-offset-2 col-md-10">  
  62.                 <input type="submit" value="Create" class="btn btn-default" />  
  63.             </div>  
  64.         </div>  
  65.     </div>  
  66. }  
  67.   
  68. <div>  
  69.     @Html.ActionLink("Back to List""Index")  
  70. </div>  
  71.   
  72. @section Scripts {  
  73.     @Scripts.Render("~/bundles/jqueryval")  
  74. }  
Now we need a different action method for the Create Button and also for returning back to the main view, in other words the index view, we called the index action that we already created in our previous article. 
  1. [HttpPost]  
  2. [ValidateAntiForgeryToken]  
  3. public ActionResult Create([Bind(Include="CustomerID,CustomerName,CustAddress,CustCity,CustPinCode,PhoneNo")] Customer customer)  
  4. {  
  5.      if (ModelState.IsValid)  
  6.      {  
  7.           db.Customers.Add(customer);  
  8.           db.SaveChanges();  
  9.           return RedirectToAction("Index");  
  10.      }  
  11.      return View(customer);  
  12. }  
This code adds the Customer entity created by the ASP.NET MVC model binder to the Customer entity set and then saves the changes to the database. (Model binder refers to the ASP.NET MVC functionality that makes it easier for you to work with data submitted by a form; a model binder converts posted form values to CLR types and es them to the action method in parameters. In this case, the model binder instantiates a Customer entity for you using property values from the Form collection.) 
 
Update the Existing Data with HttpPost

In Controllers\CustomerController.cs, the HttpGet Edit method (the one without the HttpPost attribute) uses the Find method to retrieve the selected Customer entity, as you saw in the Details method. You don't need to change this method. However, replace the HttpPost Edit action method with the following code to add a try-catch block: 
  1. public ActionResult Edit(int? id)  
  2.         {  
  3.             if (id == null)  
  4.             {  
  5.                 return new HttpStatusCodeResult(HttpStatusCode.BadRequest);  
  6.             }  
  7.             Customer customer = db.Customers.Find(id);  
  8.             if (customer == null)  
  9.             {  
  10.                 return HttpNotFound();  
  11.             }  
  12.             return View(customer);  
  13.         }  
The key value is ed to the method as the id parameter and comes from route data in the Edit hyperlink on the Index page. Also, now create the HttpPost Edit action method to update the data into the database.
  1. [HttpPost]  
  2.         [ValidateAntiForgeryToken]  
  3.         public ActionResult Edit([Bind(Include="CustomerID,CustomerName,CustAddress,CustCity,CustPinCode,PhoneNo")] Customer customer)  
  4.         {  
  5.             if (ModelState.IsValid)  
  6.             {  
  7.                 db.Entry(customer).State = EntityState.Modified;  
  8.                 db.SaveChanges();  
  9.                 return RedirectToAction("Index");  
  10.             }  
  11.             return View(customer);  
  12.         }  
This code is similar to what you saw in the HttpPost Create method. However, instead of adding the entity created by the model binder to the entity set, this code sets a flag on the entity indicating it has been changed. When the SaveChanges method is called, the Modified flag causes the Entity Framework to create SQL statements to update the database row. All columns of the database row will be updated, including those that the user didn't change and concurrency conflicts are ignored.
 
For this, we must create another view named "Edit" and provide the following code:
  1. @model EFRndProject.Models.Customer  
  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>Customer</h4>  
  17.         <hr />  
  18.         @Html.ValidationSummary(true)  
  19.         @Html.HiddenFor(model => model.CustomerID)  
  20.   
  21.         <div class="form-group">  
  22.             @Html.LabelFor(model => model.CustomerName, new { @class = "control-label col-md-2" })  
  23.             <div class="col-md-10">  
  24.                 @Html.EditorFor(model => model.CustomerName)  
  25.                 @Html.ValidationMessageFor(model => model.CustomerName)  
  26.             </div>  
  27.         </div>  
  28.   
  29.         <div class="form-group">  
  30.             @Html.LabelFor(model => model.CustAddress, new { @class = "control-label col-md-2" })  
  31.             <div class="col-md-10">  
  32.                 @Html.EditorFor(model => model.CustAddress)  
  33.                 @Html.ValidationMessageFor(model => model.CustAddress)  
  34.             </div>  
  35.         </div>  
  36.   
  37.         <div class="form-group">  
  38.             @Html.LabelFor(model => model.CustCity, new { @class = "control-label col-md-2" })  
  39.             <div class="col-md-10">  
  40.                 @Html.EditorFor(model => model.CustCity)  
  41.                 @Html.ValidationMessageFor(model => model.CustCity)  
  42.             </div>  
  43.         </div>  
  44.   
  45.         <div class="form-group">  
  46.             @Html.LabelFor(model => model.CustPinCode, new { @class = "control-label col-md-2" })  
  47.             <div class="col-md-10">  
  48.                 @Html.EditorFor(model => model.CustPinCode)  
  49.                 @Html.ValidationMessageFor(model => model.CustPinCode)  
  50.             </div>  
  51.         </div>  
  52.   
  53.         <div class="form-group">  
  54.             @Html.LabelFor(model => model.PhoneNo, new { @class = "control-label col-md-2" })  
  55.             <div class="col-md-10">  
  56.                 @Html.EditorFor(model => model.PhoneNo)  
  57.                 @Html.ValidationMessageFor(model => model.PhoneNo)  
  58.             </div>  
  59.         </div>  
  60.   
  61.         <div class="form-group">  
  62.             <div class="col-md-offset-2 col-md-10">  
  63.                 <input type="submit" value="Save" class="btn btn-default" />  
  64.             </div>  
  65.         </div>  
  66.     </div>  
  67. }  
  68.   
  69. <div>  
  70.     @Html.ActionLink("Back to List""Index")  
  71. </div>  
  72.   
  73. @section Scripts {  
  74.     @Scripts.Render("~/bundles/jqueryval")  
  75. }  
Updating the Delete Page 
 
In Controllers\CustomerController.cs, the template code for the HttpGet Delete method uses the Find method to retrieve the selected Customer entity, as you saw in the Details and Edit methods. However, to implement a custom error message when the call to SaveChanges fails, you'll add some functionality to this method and its corresponding view.

As you saw for the update and create operations, delete operations require two action methods. The method that is called in response to a GET request displays a view that gives the user a chance to approve or cancel the delete operation. If the user approves it, a POST request is created. When that happens, the HttpPost Delete method is called and then that method actually does the delete operation.
  1. public ActionResult Delete(int? id)  
  2.         {  
  3.             if (id == null)  
  4.             {  
  5.                 return new HttpStatusCodeResult(HttpStatusCode.BadRequest);  
  6.             }  
  7.             Customer customer = db.Customers.Find(id);  
  8.             if (customer == null)  
  9.             {  
  10.                 return HttpNotFound();  
  11.             }  
  12.             return View(customer);  
  13.         }  
  14.   
  15. [HttpPost, ActionName("Delete")]  
  16.         [ValidateAntiForgeryToken]  
  17.         public ActionResult DeleteConfirmed(int id)  
  18.         {  
  19.             Customer customer = db.Customers.Find(id);  
  20.             db.Customers.Remove(customer);  
  21.             db.SaveChanges();  
  22.             return RedirectToAction("Index");  
  23.         }  
The HttpPost DeleteConfirmed method code retrieves the selected entity, then calls the Remove method to set the entity's status to Deleted. When SaveChanges is called, a SQL DELETE command is generated. 
 
Now add a new view named "Delete" under the views/Customer folder and provide the following code: 
  1. @model EFRndProject.Models.Customer  
  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>Customer</h4>  
  13.     <hr />  
  14.     <dl class="dl-horizontal">  
  15.         <dt>  
  16.             @Html.DisplayNameFor(model => model.CustomerName)  
  17.         </dt>  
  18.   
  19.         <dd>  
  20.             @Html.DisplayFor(model => model.CustomerName)  
  21.         </dd>  
  22.   
  23.         <dt>  
  24.             @Html.DisplayNameFor(model => model.CustAddress)  
  25.         </dt>  
  26.   
  27.         <dd>  
  28.             @Html.DisplayFor(model => model.CustAddress)  
  29.         </dd>  
  30.   
  31.         <dt>  
  32.             @Html.DisplayNameFor(model => model.CustCity)  
  33.         </dt>  
  34.   
  35.         <dd>  
  36.             @Html.DisplayFor(model => model.CustCity)  
  37.         </dd>  
  38.   
  39.         <dt>  
  40.             @Html.DisplayNameFor(model => model.CustPinCode)  
  41.         </dt>  
  42.   
  43.         <dd>  
  44.             @Html.DisplayFor(model => model.CustPinCode)  
  45.         </dd>  
  46.   
  47.         <dt>  
  48.             @Html.DisplayNameFor(model => model.PhoneNo)  
  49.         </dt>  
  50.   
  51.         <dd>  
  52.             @Html.DisplayFor(model => model.PhoneNo)  
  53.         </dd>  
  54.   
  55.     </dl>  
  56.   
  57.     @using (Html.BeginForm()) {  
  58.         @Html.AntiForgeryToken()  
  59.   
  60.         <div class="form-actions no-color">  
  61.             <input type="submit" value="Delete" class="btn btn-default" /> |  
  62.             @Html.ActionLink("Back to List""Index")  
  63.         </div>  
  64.     }  
  65. </div>  
Ensuring that Database Connections Are Not Left Open

To ensure that database connections are properly closed and the resources they hold freed up, you need to dispose of the context instance when you are done with it.  For this, we need to add the following Dispose method in the CustomerController.
protected override  Dispose(bool disposing).
  1. {  
  2.    db.Dispose();  
  3.    base.Dispose(disposing);  
  4. }  
The base Controller class already implements the IDisposable interface, so this code simply adds an override to the Dispose(bool) method to explicitly dispose of the context instance.


Similar Articles