introduction to entity framework part 2

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

Upload: waite

Post on 22-Feb-2016

49 views

Category:

Documents


0 download

DESCRIPTION

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) - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Introduction to Entity Framework Part 2

Introduction to Entity FrameworkPart 2

CRUD ScaffoldingTom Perkins

NTPCUG

Page 2: Introduction to Entity Framework Part 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 …

Page 3: Introduction to Entity Framework Part 2

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

Page 4: Introduction to Entity Framework Part 2
Page 5: Introduction to Entity Framework Part 2
Page 6: Introduction to Entity Framework Part 2

DISPLAY COURSES EACH STUDENT IS ENROLLED IN

Objective 1

Page 7: Introduction to Entity Framework Part 2

Task: Display Student Courses

Student Details (Target) Student Details (Current)

Page 8: Introduction to Entity Framework Part 2

Modify Views\Student\Details.cshtml

• Examine code in Views\Student\Details.cshtml

Page 9: Introduction to Entity Framework Part 2

@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);}

Page 10: Introduction to Entity Framework Part 2

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>

Page 11: Introduction to Entity Framework Part 2

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

Page 12: Introduction to Entity Framework Part 2

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

Page 13: Introduction to Entity Framework Part 2
Page 14: Introduction to Entity Framework Part 2

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

Objective 2

Page 15: Introduction to Entity Framework Part 2

Module:Controllers\StudentController.cs

• replace the HttpPost Create action method with the highlighted code in Modification 2

Page 16: Introduction to Entity Framework Part 2

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.

Page 17: Introduction to Entity Framework Part 2

Security Note:

• The ValidateAntiForgeryToken attribute helps prevent cross-site request forgery (cookie modification) attacks.

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

Page 18: Introduction to Entity Framework Part 2

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>

Page 19: Introduction to Entity Framework Part 2

Run, and try to enter Student data with invalid date

Page 20: Introduction to Entity Framework Part 2

Run with corrected date

Page 21: Introduction to Entity Framework Part 2

UPDATE THE POSTING OPERATION FOR THE EDIT PAGE

Objective 3

Page 22: Introduction to Entity Framework Part 2

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

Page 23: Introduction to Entity Framework Part 2

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

Page 24: Introduction to Entity Framework Part 2

DbContext Maintains Entity State

Entities in Memory Rows in the Database

DbContext(In Sync?)

Add

SaveChanges()

SQL

INSERT

Maintains Entity State

Page 25: Introduction to Entity Framework Part 2

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

Page 26: Introduction to Entity Framework Part 2

Entity States, Continued

• Deleted– Entity has been marked for deletion– SaveChanges() issues a DELETE command

• Detached– Not being tracked by database context

Page 27: Introduction to Entity Framework Part 2

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.

Page 28: Introduction to Entity Framework Part 2

Edit a Student – Student tab, then Edit hyperlink

Page 29: Introduction to Entity Framework Part 2

Change the Enrollment Date to 9/1/2011

Page 30: Introduction to Entity Framework Part 2

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

Objective 4

Page 31: Introduction to Entity Framework Part 2

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.

Page 32: Introduction to Entity Framework Part 2

Delete Operation – Walkthru

1. Controllers\StudentController.cs – HttpGet Delete Action

2. Views\Student\Delete.cshtml3. Controllers\StudentController.cs = HttpPost

DeleteConfirmed ActionNote the [HttpPost,ActionName(“Delete”)] attribute. This ensures the request generated by the Delete view will be routed to the DeleteConfirmed action.

Page 33: Introduction to Entity Framework Part 2

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.

Page 34: Introduction to Entity Framework Part 2

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");}

Page 35: Introduction to Entity Framework Part 2

Add an Error Message

• Add to \Views\Student\Delete.cshtml

Page 36: Introduction to Entity Framework Part 2

Delete a Student …

Page 37: Introduction to Entity Framework Part 2
Page 38: Introduction to Entity Framework Part 2

Next – Paging, Filtering and Sorting

FINIS