Introduction to Entity Framework Part 2 CRUD Scaffolding Tom Perkins NTPCUG.
-
Upload
aron-porter -
Category
Documents
-
view
221 -
download
0
Transcript of Introduction to Entity Framework Part 2 CRUD Scaffolding Tom Perkins NTPCUG.
Introduction to Entity FrameworkPart 2
CRUD ScaffoldingTom 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)– MVC scaffolding feature automatically creates basid
code for you in Views and Controllers• Pages we’ll create follow …
Note the display of the courses for which the student is enrolled.
DISPLAY COURSES EACH STUDENT IS ENROLLED IN
Objective 1
Task: Display Student Courses
Student Details (Target) Student Details (Current)
Modify Views\Student\Details.cshtml
• Examine code in Views\Student\Details.cshtml
@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);}
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>
Add code in Mod 1
Lazy Loading – a new query is generated each time you access the Enrollments navigation property.
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.)
UPDATE THE ‘CREATE’ PAGE REMOVE ACCESS TO ‘ID’, ADD TRY-CATCH BLOCK
Objective 2
Module:Controllers\StudentController.cs
• replace the HttpPost Create action method with the highlighted code in Modification 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.
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.
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>
Run, and try to enter Student data with invalid date
Run with corrected date
UPDATE THE POSTING OPERATION FOR THE EDIT PAGE
Objective 3
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
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
DbContext Maintains Entity State
Entities in Memory Rows in the Database
DbContext(In Sync?)
Add
SaveChanges()
SQL
INSERT
Maintains Entity State
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
Entity States, Continued
• Deleted– Entity has been marked for deletion– SaveChanges() issues a DELETE command
• Detached– Not being tracked by database context
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.
Edit a Student – Student tab, then Edit hyperlink
Change the Enrollment Date to 9/1/2011
UPDATE THE DELETE PAGE - ADD A CUSTOM ERROR MESSAGE WHEN SAVECHANGES() FAILS
Objective 4
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.
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.
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.
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");}
Add an Error Message
• Add to \Views\Student\Delete.cshtml
Delete a Student …
Next – Paging, Filtering and Sorting
FINIS