Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Entity Framework Part 2 CRUD Scaffolding Tom Perkins NTPCUG.

Similar presentations


Presentation on theme: "Introduction to Entity Framework Part 2 CRUD Scaffolding Tom Perkins NTPCUG."— Presentation transcript:

1 Introduction to Entity Framework Part 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

5

6 DISPLAY COURSES EACH STUDENT IS ENROLLED IN Objective 1

7 Task: Display Student Courses Student Details (Target)Student Details (Current)

8 Modify Views\Student\Details.cshtml Examine code in Views\Student\Details.cshtml

9 @model Statement @model ContosoUniversity.Models.Student indicates 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); }

10 Open Views\Student\Details.cshtml Each field is displayed using a DisplayFor helper. @Html.DisplayNameFor(model => model.LastName) @Html.DisplayFor(model => model.LastName)

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

12 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.)

13

14 UPDATE THE ‘CREATE’ PAGE REMOVE ACCESS TO ‘ID’, ADD TRY-CATCH BLOCK Objective 2

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

16 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.

17 Security Note: The ValidateAntiForgeryToken attribute helps prevent cross-site request forgery (cookie modification) attacks.cross-site request forgery It requires a corresponding Html.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.

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

19 Run, and try to enter Student data with invalid date

20 Run with corrected date

21 UPDATE THE POSTING OPERATION FOR THE EDIT PAGE Objective 3

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

23 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

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

25 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

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

27 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.

28 Edit a Student – Student tab, then Edit hyperlink

29 Change the Enrollment Date to 9/1/2011

30 UPDATE THE DELETE PAGE - ADD A CUSTOM ERROR MESSAGE WHEN SAVECHANGES() FAILS Objective 4

31 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.

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

33 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.

34 Replace the HttpGet DeleteConfirmed 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"); }

35 Add an Error Message Add to \Views\Student\Delete.cshtml

36 Delete a Student …

37

38 Next – Paging, Filtering and Sorting FINIS


Download ppt "Introduction to Entity Framework Part 2 CRUD Scaffolding Tom Perkins NTPCUG."

Similar presentations


Ads by Google