Introduction
In this article we'll learn how to do Create, Read, Update and Delete (CRUD) operations with the Entity Framework Data Model in the ASP.NET Web Application based on the MVC Project Template in Visual Studio 2013. As I described in the MVC with Entity Framework Data Model, we can create a MVC Application with Entity Framework 6, therefore here we perform the CRUD functionality.
So, let's proceed with the following section:
- Updating the application and Perform CRUD Operations
Updating the application and doing CRUD Operations
At first we update our application to designate more briefly. We can also modify our pages to define more details of students about their enrollments and courses in their details. Use the following procedure to update the details page.
Editing Details Page
As we define the enrollments property in the student that hold the collection, so here we define it in the details page so that we can show which courses the student enrolls in.
Step 1: You can the Details Action in the Controllers\StudentController.cs page that it used in the Find() to get the student entity.
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Student student = db.Students.Find(id);
if (student == null)
{
return HttpNotFound();
}
return View(student);
}
Step 2: Open the Views\Student\Details.cshtml page and add the highlighted code below:
<dd>
@Html.DisplayFor(model => model.EnrollmentDate)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Enrollments)
</dt>
<dd>
<table class="table">
<tr>
<th>Course Name</th>
<th>Grade</th>
</tr>
@foreach (var items in Model.Enrollments)
{
<tr>
<td>
@Html.DisplayFor(modelitems => items.Course.Name)
</td>
<td>
@Html.DisplayFor(mdoelitems => items.Grade)
</td>
</tr>
}
</table>
</dd>
You can press "Ctrl+K+D" to apply the indentation in your code. In the code above the Enrollments navigation property is used to display the Course name and Grade of the student, if the student enrolls in one or more courses then it is displayed again by the foreach loop. All of this data is retrieved from the database automatically when it is needed.
Step 3: Press "Ctrl+F5" to run the application.
Step 4: Click on the "Students" link and then we want the details of Nimit. So, click on the details link:
In the preceding screenshot, you can see that the student enrollments in various courses and grade. It shows the list of enrollments for the selected student.
Editing Create Page
Step 1: Open the Controllers\StudentController.cs page and find the Create Action and modify it with the highlighted code below:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include="FirstName,LastName,EnrollmentDate")] Student student)
{
try
{
if (ModelState.IsValid)
{
db.Students.Add(student);
db.SaveChanges();
return RedirectToAction("Index");
}
}
catch (DataException /*dataex*/)
{
ModelState.AddModelError("","Unable to save changes. Try again or Contact to the Administrator");
}
return View(student);
}
The code above will add the Student entity in the Student entity set that is created by the MVC model binder and save the changes. We remove the ID because it is the primary key column and when the new row is inserted, SQL Server will set this automatically. The user cannot set the ID value from Input.
Step 2: Run the application and click on "Create new link".
Step 3: In Create New page we can show the server-side validation by entering the wrong date as shown below:
You can see the Server-Side validation (by-default) in the code below:
if (ModelState.IsValid)
{
db.Students.Add(student);
db.SaveChanges();
return RedirectToAction("Index");
}
Step 4: Enter the valid date and you can see the added record as in the following:
Editing Edit Page
We add the "try-catch" block here to update the Edit page. It is optional. It uses the Find() to get the Student entity.
Step 1: Modify your code with the highlighted code below:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include="ID,FirstName,LastName,EnrollmentDate")] Student student)
{
try
{
if (ModelState.IsValid)
{
db.Entry(student).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
}
catch(DataException /*DataEx*/)
{
ModelState.AddModelError("", "Unable to save changes. Try again or Contact to the Administrator");
}
return View(student);
}
The code above sets a flag on the entity and indicates that this has been changed. When the flag has been changed the SaveChanges() runs and the modified flag is responsible for informing the Entity Framework to run the update query in the SQL statement and update the row.
Step 2: Press "Ctrl+F5" to run the application and click on the "Edit" link to edit the student.
Step 3: You can see the Edited record in the following:
Editing Delete Page
The Delete method in the StudentController.cs page uses the Find() to delete the row as we saw above in the "Details" and "Create" pages. We can add some custom error message if the SaveChanges() failed to execute.
There are two types of action methods called in here. When the method calls and the response is GET, it shows the confirmation page to delete the selected data and when the user accepts it, a POST request is created. The HttpPost Delete method is called and then delete operation is actually performed.
We'll add a "try-catch" block here to show the custom message if any error occur during the update of the database.
Step 1: Find and replace the Delete action method, with the highlighted code below:
public ActionResult Delete(int? id, bool? ErrorinSaveChanges=false)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
if (ErrorinSaveChanges.GetValueOrDefault())
{
ViewBag.ErrorMessage = "Failed to Delete. Try again or Contact to System Administrator";
}
Student student = db.Students.Find(id);
if (student == null)
{
return HttpNotFound();
}
return View(student);
}
Step 2: Modify the HttpPost DeleteConfirmed action method with the code below:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(int id)
{
try
{
Student student = db.Students.Find(id);
db.Students.Remove(student);
db.SaveChanges();
}
catch (DataException /*DataEx*/)
{
return RedirectToAction("Delete", new { id = id, errorinsavechanges = true});
}
return RedirectToAction("Index");
}
The code above gets the selected entity and calls Remove() to change the status to "Delete". Now the SQL DELETE command executes, when the SaveChanges() method runs.
Step 3: Open the Views\Student\Delete.cshtml page and modify it with the highlighted code below:
<h2>Delete</h2>
<p class="error">@ViewBag.ErrorMessage</p>
<h3>Are you sure you want to delete this?</h3>
Step 4: Run the application and open "Students" link. Click on the "Delete" link to delete the data.
Step 5: When in the conformation page and you click on Delete, the data is deleted and the Index page is displayed.
Summary
This article has explained how to do CRUD operations in ASP.NET MVC Applications. You can also update and generate the elements. Now, in the article we'll perform the paging and sorting techniques. Thanks for reading.