1 / 38

Introduction to Entity Framework Part 2

Introduction to Entity Framework Part 2. CRUD Scaffolding Tom Perkins NTPCUG. Quo Vadis. Previously (Part 01), we created an MVC application We stored and displayed data using SQL Server LocalDB This tutorial Develop CRUD capabililty (Create, Read, Update, and Delete pages)

waite
Download Presentation

Introduction to Entity Framework Part 2

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Introduction to Entity FrameworkPart 2 CRUD Scaffolding Tom Perkins NTPCUG

  2. Quo Vadis • Previously (Part 01), we created an MVC application • We stored and displayed data using SQL Server LocalDB • This tutorial • Develop CRUD capabililty (Create, Read, Update, and Delete pages) • MVC scaffolding feature automatically creates basid code for you in Views and Controllers • Pages we’ll create follow …

  3. Note the display of the courses for which the student is enrolled.

  4. Objective 1 Display courses each student is enrolled in

  5. Task: Display Student Courses Student Details (Target) Student Details (Current)

  6. Modify Views\Student\Details.cshtml • Examine code in Views\Student\Details.cshtml

  7. @model Statement • @model ContosoUniversity.Models.Studentindicates you want to use the ContosoUniversity.Models.Student object as data for this view • This object is created in the Controllers\StudentController.cs class – the id field is provided by the model binder using routing data. 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); }

  8. Open Views\Student\Details.cshtml • Each field is displayed using a DisplayFor helper. <dt> @Html.DisplayNameFor(model => model.LastName) </dt> <dd> @Html.DisplayFor(model => model.LastName) </dd>

  9. Add code in Mod 1 Lazy Loading – a new query is generated each time you access the Enrollments navigation property.

  10. Run the Application • (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 clickView, and then click View in Browser.)

  11. Objective 2 Update the ‘create’ page remove access to ‘ID’, add try-catch block

  12. Module:Controllers\StudentController.cs • replace the HttpPost Create action method with the highlighted code in Modification 2

  13. Walkthru: Modified Controllers\StudentController.cs • Read through code • The model binder • Coverts posted form values into CLR types (objects) • Passes them to an action method in parameters • Here, model binder creates a Student entity based on property values from the Form collection • Note: ID has been removed. ID set by SQL, not by user.

  14. Security Note: •  The ValidateAntiForgeryToken attribute helps prevent cross-site request forgery (cookie modification) attacks. • It requires a correspondingHtml.AntiForgeryToken() statement in the view. • Bind attribute prevents overposting (i.e, Fiddler attack to modify a secret salary field.) Only fields listed in Bind are updated. • Try-Catch block could also log the error.

  15. Walkthru\Views\Student\Create.cshtml • Note EditFor and ValidationMessageFor helpers instead of DisplayFor. • Also note @HtmlAntiForgeryToken() • Relevant code: <div class="form-group"> @Html.LabelFor(model => model.LastName, new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.LastName) @Html.ValidationMessageFor(model => model.LastName) </div> </div>

  16. Run, and try to enter Student data with invalid date

  17. Run with corrected date

  18. Objective 3 Update the Posting operation for the edit page

  19. Module: Controllers\StudentController.cs • HttpGet Edit method does not need to be modified. • replace the HttpPostEdit action method with the code highlighted below in Modification 3 to add a try-catch block

  20. Walkthru • Similar to Create changes • Difference: Entity not saved; it is marked as ‘Modified’. • SaveChanges() method will generate SQL statements to update row in table • All columns in row are updated, including those the user did not change • Currency conflicts are ignored

  21. DbContext Maintains Entity State DbContext (In Sync?) Entities in Memory Rows in the Database Maintains Entity State SQL INSERT Add SaveChanges()

  22. Entity States • Added • Entity doesn’t exist in database. • SaveChanges() issues a SQL INSERT query. • Unchanged • SaveChanges() – nothing is done • This is the initial state for an entity • Modified • Some or all property values have been changed • SaveChanges() issues an UPDATE query

  23. Entity States, Continued • Deleted • Entity has been marked for deletion • SaveChanges() issues a DELETE command • Detached • Not being tracked by database context

  24. Entity State Setting • Desktop Apps • Entity State is set automatically by Entity Framework • Web Apps • Disconnected nature • DbContext is disposed after page is rendered • Entity State must be set manually to ‘Modified’ • All columns in row will be updated • To update only columns modified by user, see more info on the Attach() method.

  25. Edit a Student – Student tab, then Edit hyperlink

  26. Change the Enrollment Date to 9/1/2011

  27. Objective 4 Update the delete page - Add a custom error message when Savechanges() fails

  28. DELETE Operations • Require 2 action methods • Give the user a chance to approve or disapprove the DELETE • If approved, a POST request is created • HttpPost Delete method is called • That method performs the Delete operation.

  29. Delete Operation – Walkthru • Controllers\StudentController.cs – HttpGet Delete Action • Views\Student\Delete.cshtml • Controllers\StudentController.cs = HttpPostDeleteConfirmed Action Note the [HttpPost,ActionName(“Delete”)] attribute. This ensures the request generated by the Delete view will be routed to the DeleteConfirmed action.

  30. Controllers\StudentController.cs – HttpGet Delete action • Apply the changes highlighted below to the HttpGet Delete action of Controllers\StudentController.cs -- code is in Modification 4.

  31. Replace the HttpGetDeleteConfirmed Method [HttpPost] [ValidateAntiForgeryToken] public ActionResult Delete(int id) { try { Student student = db.Students.Find(id); db.Students.Remove(student); db.SaveChanges(); } catch (DataException/* dex */) { //Log the error (uncomment dex variable name and add a line here to write a log. return RedirectToAction("Delete", new { id = id, saveChangesError = true }); } return RedirectToAction("Index"); }

  32. Add an Error Message • Add to \Views\Student\Delete.cshtml

  33. Delete a Student …

  34. Next – Paging, Filtering and Sorting FINIS

More Related