Implementing Basic CRUD Functionality with the Entity Framework in ASP.NET MVC Application
by Tom Dykstra
Download Completed Project or Download PDF
The Contoso University sample web application demonstrates how to create ASP.NET MVC 5 applications using the Entity Framework 6 Code First and Visual Studio 2013. For information about the tutorial series, see the first tutorial in the series.
In the previous tutorial you created an MVC application that stores and displays data using the Entity Framework and SQL Server LocalDB. In this tutorial you’ll review and customize the CRUD (create, read, update, delete) code that the MVC scaffolding automatically creates for you in controllers and views.
[!NOTE] It’s a common practice to implement the repository pattern in order to create an abstraction layer between your controller and the data access layer. To keep these tutorials simple and focused on teaching how to use the Entity Framework itself, they don’t use repositories. For information about how to implement repositories, see the ASP.NET Data Access Content Map.
In this tutorial, you’ll create the following web pages:



Create a Details Page
The scaffolded code for the Students Index page left out the Enrollments property, because that property holds a collection. In the Details page you’ll display the contents of the collection in an HTML table.
In Controllers.cs, the action method for the Details view uses the Find method to retrieve a single Student entity.
[!code-csharpMain]
1: public ActionResult Details(int? id)
2: {
3: if (id == null)
4: {
5: return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
6: }
7: Student student = db.Students.Find(id);
8: if (student == null)
9: {
10: return HttpNotFound();
11: }
12: return View(student);
13: }
The key value is passed to the method as the id parameter and comes from route data in the Details hyperlink on the Index page.
Tip: Route data
Route data is data that the model binder found in a URL segment specified in the routing table. For example, the default route specifies controller, action, and id segments:
[!code-csharpMain]
1: routes.MapRoute(
2: name: "Default",
3: url: "{controller}/{action}/{id}",
4: defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
5: );
In the following URL, the default route maps Instructor as the controller, Index as the action and 1 as the id; these are route data values.
http://localhost:1230/Instructor/Index/1?courseID=2021
“?courseID=2021” is a query string value. The model binder will also work if you pass the id as a query string value:
http://localhost:1230/Instructor/Index?id=1&CourseID=2021
The URLs are created by ActionLink statements in the Razor view. In the following code, the id parameter matches the default route, so id is added to the route data.
[!code-cshtmlMain]
1: @Html.ActionLink("Select", "Index", new { id = item.PersonID })
In the following code, courseID doesn’t match a parameter in the default route, so it’s added as a query string.
[!code-cshtmlMain]
1: @Html.ActionLink("Select", "Index", new { courseID = item.CourseID })
Open Views.cshtml. Each field is displayed using a
[!code-cshtmlMain]DisplayForhelper, as shown in the following example:1: <dt>2: @Html.DisplayNameFor(model => model.LastName)
3: </dt>4: <dd>5: @Html.DisplayFor(model => model.LastName)
6: </dd>After the
EnrollmentDatefield and immediately before the closing</dl>tag, add the highlighted code to display a list of enrollments, as shown in the following example:[!code-cshtmlMain]
1: <dt>2: @Html.DisplayNameFor(model => model.EnrollmentDate)
3: </dt>4:5: <dd>6: @Html.DisplayFor(model => model.EnrollmentDate)
7: </dd>8: <dt>9: @Html.DisplayNameFor(model => model.Enrollments)
10: </dt>11: <dd>12: <table class="table">
13: <tr>14: <th>Course Title</th>15: <th>Grade</th>16: </tr>17: @foreach (var item in Model.Enrollments)
18: {19: <tr>20: <td>21: @Html.DisplayFor(modelItem => item.Course.Title)
22: </td>23: <td>24: @Html.DisplayFor(modelItem => item.Grade)
25: </td>26: </tr>27: }28: </table>29: </dd>30: </dl>31: </div>32: <p>33: @Html.ActionLink("Edit", "Edit", new { id = Model.ID }) |
34: @Html.ActionLink("Back to List", "Index")
35: </p>If code indentation is wrong after you paste the code, press CTRL-K-D to correct it.
This code loops through the entities in theEnrollmentsnavigation property. For eachEnrollmententity in the property, it displays the course title and the grade. The course title is retrieved from theCourseentity that’s stored in theCoursenavigation property of theEnrollmentsentity. All of this data is retrieved from the database automatically when it’s needed. (In other words, you are using lazy loading here. You did not specify eager loading for theCoursesnavigation property, so the enrollments were not retrieved in the same query that got the students. Instead, the first time you try to access theEnrollmentsnavigation property, a new query is sent to the database to retrieve the data. You can read more about lazy loading and eager loading in the Reading Related Data tutorial later in this series.)Run the page by selecting the Students tab and clicking a Details link for Alexander Carson. (If you press CTRL+F5 while the Details.cshtml file is open, you’ll get an HTTP 400 error because Visual Studio tries to run the Details page but it wasn’t reached from a link that specifies the student to display. In that case, just remove “Student/Details” from the URL and try again, or close the browser, right-click the project, and click View, and then click View in Browser.)
You see the list of courses and grades for the selected student:

Student_Details_page
Update the Create Page
In Controllers.cs, replace the
HttpPost``Createaction method with the following code to add atry-catchblock and removeIDfrom the Bind attribute for the scaffolded method:[!code-csharpMain]
1: [HttpPost]2: [ValidateAntiForgeryToken]3: public ActionResult Create([Bind(Include = "LastName, FirstMidName, EnrollmentDate")]Student student)
4: {5: try
6: {7: if (ModelState.IsValid)
8: {9: db.Students.Add(student);10: db.SaveChanges();11: return RedirectToAction("Index");
12: }13: }14: catch (DataException /* dex */)
15: {16: //Log the error (uncomment dex variable name and add a line here to write a log.
17: ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
18: }19: return View(student);
20: }This code adds the
Studententity created by the ASP.NET MVC model binder to theStudentsentity 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 passes them to the action method in parameters. In this case, the model binder instantiates aStudententity for you using property values from theFormcollection.)You removed
IDfrom the Bind attribute becauseIDis the primary key value which SQL Server will set automatically when the row is inserted. Input from the user does not set theIDvalue.### Security warning - The
ValidateAntiForgeryTokenattribute helps prevent cross-site request forgery attacks. It requires a correspondingHtml.AntiForgeryToken()statement in the view, which you’ll see later.The
Bindattribute is one way to protect against over-posting in create scenarios. For example, suppose theStudententity includes aSecretproperty that you don’t want this web page to set.[!code-csharpMain]
1: public class Student
2: {3: public int ID { get; set; }
4: public string LastName { get; set; }
5: public string FirstMidName { get; set; }
6: public DateTime EnrollmentDate { get; set; }
7: public string Secret { get; set; }
8:9: public virtual ICollection<Enrollment> Enrollments { get; set; }
10: }Even if you don’t have a
Secretfield on the web page, a hacker could use a tool such as fiddler, or write some JavaScript, to post aSecretform value. Without the Bind attribute limiting the fields that the model binder uses when it creates aStudentinstance, the model binder would pick up thatSecretform value and use it to create theStudententity instance. Then whatever value the hacker specified for theSecretform field would be updated in your database. The following image shows the fiddler tool adding theSecretfield (with the value “OverPost”) to the posted form values.
The value “OverPost” would then be successfully added to the
Secretproperty of the inserted row, although you never intended that the web page be able to set that property.It’s a security best practice to use the
Includeparameter with theBindattribute to whitelist fields. It’s also possible to use theExcludeparameter to blacklist fields you want to exclude. The reasonIncludeis more secure is that when you add a new property to the entity, the new field is not automatically protected by anExcludelist.You can prevent overposting in edit scenarios is by reading the entity from the database first and then calling
TryUpdateModel, passing in an explicit allowed properties list. That is the method used in these tutorials.An alternative way to prevent overposting that is preferred by many developers is to use view models rather than entity classes with model binding. Include only the properties you want to update in the view model. Once the MVC model binder has finished, copy the view model properties to the entity instance, optionally using a tool such as AutoMapper. Use db.Entry on the entity instance to set its state to Unchanged, and then set Property(“PropertyName”).IsModified to true on each entity property that is included in the view model. This method works in both edit and create scenarios.
Other than the
Bindattribute, thetry-catchblock is the only change you’ve made to the scaffolded code. If an exception that derives from DataException is caught while the changes are being saved, a generic error message is displayed. DataException exceptions are sometimes caused by something external to the application rather than a programming error, so the user is advised to try again. Although not implemented in this sample, a production quality application would log the exception. For more information, see the Log for insight section in Monitoring and Telemetry (Building Real-World Cloud Apps with Azure).The code in Views.cshtml is similar to what you saw in Details.cshtml, except that
EditorForandValidationMessageForhelpers are used for each field instead ofDisplayFor. Here is the relevant code:[!code-cshtmlMain]
1: <div class="form-group">
2: @Html.LabelFor(model => model.LastName, new { @class = "control-label col-md-2" })
3: <div class="col-md-10">
4: @Html.EditorFor(model => model.LastName)
5: @Html.ValidationMessageFor(model => model.LastName)
6: </div>7: </div>Create.chstml also includes
No changes are required in Create.cshtml.@Html.AntiForgeryToken(), which works with theValidateAntiForgeryTokenattribute in the controller to help prevent cross-site request forgery attacks.- Run the page by selecting the Students tab and clicking Create New.
Enter names and an invalid date and click Create to see the error message.

Students_Create_page_error_message This is server-side validation that you get by default; in a later tutorial you’ll see how to add attributes that will generate code for client-side validation also. The following highlighted code shows the model validation check in the Create method.
[!code-csharpMain]1: if (ModelState.IsValid)
2: {3: db.Students.Add(student);4: db.SaveChanges();5: return RedirectToAction("Index");
6: }Change the date to a valid value and click Create to see the new student appear in the Index page.

Students_Index_page_with_new_student
Update the Edit HttpPost Method
In Controllers.cs, the HttpGet Edit method (the one without the HttpPost attribute) uses the Find method to retrieve the selected Student 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:
[!code-csharpMain]
1: [HttpPost, ActionName("Edit")]
2: [ValidateAntiForgeryToken]
3: public ActionResult EditPost(int? id)
4: {
5: if (id == null)
6: {
7: return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
8: }
9: var studentToUpdate = db.Students.Find(id);
10: if (TryUpdateModel(studentToUpdate, "",
11: new string[] { "LastName", "FirstMidName", "EnrollmentDate" }))
12: {
13: try
14: {
15: db.SaveChanges();
16:
17: return RedirectToAction("Index");
18: }
19: catch (DataException /* dex */)
20: {
21: //Log the error (uncomment dex variable name and add a line here to write a log.
22: ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
23: }
24: }
25: return View(studentToUpdate);
26: }
These changes implement a security best practice to prevent overposting, The scaffolder generated a Bind attribute and added the entity created by the model binder to the entity set with a Modified flag. That code is no longer recommended because the Bind attribute clears out any pre-existing data in fields not listed in the Include parameter. In the future, the MVC controller scaffolder will be updated so that it doesn’t generate Bind attributes for Edit methods.
The new code reads the existing entity and calls TryUpdateModel to update fields from user input in the posted form data. The Entity Framework’s automatic change tracking sets the Modified flag on the entity. When the SaveChanges method is called, the Modified flag causes the Entity Framework to create SQL statements to update the database row. Concurrency conflicts are ignored, and all columns of the database row are updated, including those that the user didn’t change. (A later tutorial shows how to handle concurrency conflicts, and if you only want individual fields to be updated in the database, you can set the entity to Unchanged and set individual fields to Modified.)
As a best practice to prevent overposting, the fields that you want to be updateable by the Edit page are whitelisted in the TryUpdateModel parameters. Currently there are no extra fields that you’re protecting, but listing the fields that you want the model binder to bind ensures that if you add fields to the data model in the future, they’re automatically protected until you explicitly add them here.
As a result of these changes, the method signature of the HttpPost Edit method is the same as the HttpGet edit method; therefore you’ve renamed the method EditPost.
[!TIP]
Entity States and the Attach and SaveChanges Methods
The database context keeps track of whether entities in memory are in sync with their corresponding rows in the database, and this information determines what happens when you call the
SaveChangesmethod. For example, when you pass a new entity to the Add method, that entity’s state is set toAdded. Then when you call the SaveChanges method, the database context issues a SQLINSERTcommand.An entity may be in one of thefollowing states:
Added. The entity does not yet exist in the database. TheSaveChangesmethod must issue anINSERTstatement.Unchanged. Nothing needs to be done with this entity by theSaveChangesmethod. When you read an entity from the database, the entity starts out with this status.Modified. Some or all of the entity’s property values have been modified. TheSaveChangesmethod must issue anUPDATEstatement.Deleted. The entity has been marked for deletion. TheSaveChangesmethod must issue aDELETEstatement.Detached. The entity isn’t being tracked by the database context.In a desktop application, state changes are typically set automatically. In a desktop type of application, you read an entity and make changes to some of its property values. This causes its entity state to automatically be changed to
Modified. Then when you callSaveChanges, the Entity Framework generates a SQLUPDATEstatement that updates only the actual properties that you changed.The disconnected nature of web apps doesn’t allow for this continuous sequence. The DbContext that reads an entity is disposed after a page is rendered. When the
HttpPostEditaction method is called, a new request is made and you have a new instance of the DbContext, so you have to manually set the entity state toModified.Then when you callSaveChanges, the Entity Framework updates all columns of the database row, because the context has no way to know which properties you changed.If you want the SQL
Updatestatement to update only the fields that the user actually changed, you can save the original values in some way (such as hidden fields) so that they are available when theHttpPostEditmethod is called. Then you can create aStudententity using the original values, call theAttachmethod with that original version of the entity, update the entity’s values to the new values, and then callSaveChanges.For more information, see Entity states and SaveChanges and Local Data in the MSDN Data Developer Center.
The HTML and Razor code in Views.cshtml is similar to what you saw in Create.cshtml, and no changes are required.
Run the page by selecting the Students tab and then clicking an Edit hyperlink.

Change some of the data and click Save. You see the changed data in the Index page.

Updating the Delete Page
In Controllers.cs, the template code for the HttpGet Delete method uses the Find method to retrieve the selected Student 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 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 performs the delete operation.
You’ll add a try-catch block to the HttpPost Delete method to handle any errors that might occur when the database is updated. If an error occurs, the HttpPost Delete method calls the HttpGet Delete method, passing it a parameter that indicates that an error has occurred. The HttpGet Delete method then redisplays the confirmation page along with the error message, giving the user an opportunity to cancel or try again.
Replace the
HttpGetDeleteaction method with the following code, which manages error reporting:[!code-csharpMain]
This code accepts an optional parameter that indicates whether the method was called after a failure to save changes. This parameter is1: public ActionResult Delete(int? id, bool? saveChangesError=false)
2: {3: if (id == null)
4: {5: return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
6: }7: if (saveChangesError.GetValueOrDefault())
8: {9: ViewBag.ErrorMessage = "Delete failed. Try again, and if the problem persists see your system administrator.";
10: }11: Student student = db.Students.Find(id);12: if (student == null)
13: {14: return HttpNotFound();
15: }16: return View(student);
17: }falsewhen theHttpGetDeletemethod is called without a previous failure. When it is called by theHttpPostDeletemethod in response to a database update error, the parameter istrueand an error message is passed to the view.
Replace the
HttpPostDeleteaction method (namedDeleteConfirmed) with the following code, which performs the actual delete operation and catches any database update errors.[!code-csharpMain]
1: [HttpPost]2: [ValidateAntiForgeryToken]3: public ActionResult Delete(int id)
4: {5: try
6: {7: Student student = db.Students.Find(id);8: db.Students.Remove(student);9: db.SaveChanges();10: }11: catch (DataException/* dex */)
12: {13: //Log the error (uncomment dex variable name and add a line here to write a log.
14: return RedirectToAction("Delete", new { id = id, saveChangesError = true });
15: }16: return RedirectToAction("Index");
17: }This code retrieves the selected entity, then calls the Remove method to set the entity’s status to
Deleted. WhenSaveChangesis called, a SQLDELETEcommand is generated. You have also changed the action method name fromDeleteConfirmedtoDelete. The scaffolded code named theHttpPostDeletemethodDeleteConfirmedto give theHttpPostmethod a unique signature. ( The CLR requires overloaded methods to have different method parameters.) Now that the signatures are unique, you can stick with the MVC convention and use the same name for theHttpPostandHttpGetdelete methods.If improving performance in a high-volume application is a priority, you could avoid an unnecessary SQL query to retrieve the row by replacing the lines of code that call the
FindandRemovemethods with the following code:[!code-csharpMain]
1: Student studentToDelete = new Student() { ID = id };
2: db.Entry(studentToDelete).State = EntityState.Deleted;This code instantiates a
As noted, theStudententity using only the primary key value and then sets the entity state toDeleted. That’s all that the Entity Framework needs in order to delete the entity.HttpGetDeletemethod doesn’t delete the data. Performing a delete operation in response to a GET request (or for that matter, performing any edit operation, create operation, or any other operation that changes data) creates a security risk. For more information, see ASP.NET MVC Tip #46 — Don’t use Delete Links because they create Security Holes on Stephen Walther’s blog.In Views.cshtml, add an error message between the
h2heading and theh3heading, as shown in the following example:[!code-cshtmlMain]
1: <h2>Delete</h2>2: <p class="error">@ViewBag.ErrorMessage</p>
3: <h3>Are you sure you want to delete this?</h3>Run the page by selecting the Students tab and clicking a Delete hyperlink:

Click Delete. The Index page is displayed without the deleted student. (You’ll see an example of the error handling code in action in the concurrency tutorial.)
Closing Database Connections
To close database connections and free up the resources they hold as soon as possible, dispose the context instance when you are done with it. That is why the scaffolded code provides a Dispose method at the end of the StudentController class in StudentController.cs, as shown in the following example:
[!code-csharpMain]
1: protected override void Dispose(bool disposing)
2: {
3: db.Dispose();
4: base.Dispose(disposing);
5: }
The base Controller class already implements the IDisposable interface, so this code simply adds an override to the Dispose(bool) method to explicitly dispose the context instance.
By default the Entity Framework implicitly implements transactions. In scenarios where you make changes to multiple rows or tables and then call SaveChanges, the Entity Framework automatically makes sure that either all of your changes succeed or all fail. If some changes are done first and then an error happens, those changes are automatically rolled back. For scenarios where you need more control – for example, if you want to include operations done outside of Entity Framework in a transaction – see Working with Transactions on MSDN.
Summary
You now have a complete set of pages that perform simple CRUD operations for Student entities. You used MVC helpers to generate UI elements for data fields. For more information about MVC helpers, see Rendering a Form Using HTML Helpers (the page is for MVC 3 but is still relevant for MVC 5).
In the next tutorial you’ll expand the functionality of the Index page by adding sorting and paging.
Please leave feedback on how you liked this tutorial and what we could improve. You can also request new topics at Show Me How With Code.
Links to other Entity Framework resources can be found in ASP.NET Data Access - Recommended Resources.
)
|
|