introduction to entity framework part 2 crud scaffolding tom perkins ntpcug
TRANSCRIPT
![Page 1: Introduction to Entity Framework Part 2 CRUD Scaffolding Tom Perkins NTPCUG](https://reader036.vdocuments.site/reader036/viewer/2022062321/56649eb45503460f94bbba24/html5/thumbnails/1.jpg)
Introduction to Entity FrameworkPart 2
CRUD ScaffoldingTom Perkins
NTPCUG
![Page 2: Introduction to Entity Framework Part 2 CRUD Scaffolding Tom Perkins NTPCUG](https://reader036.vdocuments.site/reader036/viewer/2022062321/56649eb45503460f94bbba24/html5/thumbnails/2.jpg)
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 CRUD Scaffolding Tom Perkins NTPCUG](https://reader036.vdocuments.site/reader036/viewer/2022062321/56649eb45503460f94bbba24/html5/thumbnails/3.jpg)
Note the display of the courses for which the student is enrolled.
![Page 4: Introduction to Entity Framework Part 2 CRUD Scaffolding Tom Perkins NTPCUG](https://reader036.vdocuments.site/reader036/viewer/2022062321/56649eb45503460f94bbba24/html5/thumbnails/4.jpg)
![Page 5: Introduction to Entity Framework Part 2 CRUD Scaffolding Tom Perkins NTPCUG](https://reader036.vdocuments.site/reader036/viewer/2022062321/56649eb45503460f94bbba24/html5/thumbnails/5.jpg)
![Page 6: Introduction to Entity Framework Part 2 CRUD Scaffolding Tom Perkins NTPCUG](https://reader036.vdocuments.site/reader036/viewer/2022062321/56649eb45503460f94bbba24/html5/thumbnails/6.jpg)
DISPLAY COURSES EACH STUDENT IS ENROLLED IN
Objective 1
![Page 7: Introduction to Entity Framework Part 2 CRUD Scaffolding Tom Perkins NTPCUG](https://reader036.vdocuments.site/reader036/viewer/2022062321/56649eb45503460f94bbba24/html5/thumbnails/7.jpg)
Task: Display Student Courses
Student Details (Target) Student Details (Current)
![Page 8: Introduction to Entity Framework Part 2 CRUD Scaffolding Tom Perkins NTPCUG](https://reader036.vdocuments.site/reader036/viewer/2022062321/56649eb45503460f94bbba24/html5/thumbnails/8.jpg)
Modify Views\Student\Details.cshtml
• Examine code in Views\Student\Details.cshtml
![Page 9: Introduction to Entity Framework Part 2 CRUD Scaffolding Tom Perkins NTPCUG](https://reader036.vdocuments.site/reader036/viewer/2022062321/56649eb45503460f94bbba24/html5/thumbnails/9.jpg)
@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 CRUD Scaffolding Tom Perkins NTPCUG](https://reader036.vdocuments.site/reader036/viewer/2022062321/56649eb45503460f94bbba24/html5/thumbnails/10.jpg)
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 CRUD Scaffolding Tom Perkins NTPCUG](https://reader036.vdocuments.site/reader036/viewer/2022062321/56649eb45503460f94bbba24/html5/thumbnails/11.jpg)
Add code in Mod 1
Lazy Loading – a new query is generated each time you access the Enrollments navigation property.
![Page 12: Introduction to Entity Framework Part 2 CRUD Scaffolding Tom Perkins NTPCUG](https://reader036.vdocuments.site/reader036/viewer/2022062321/56649eb45503460f94bbba24/html5/thumbnails/12.jpg)
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 CRUD Scaffolding Tom Perkins NTPCUG](https://reader036.vdocuments.site/reader036/viewer/2022062321/56649eb45503460f94bbba24/html5/thumbnails/13.jpg)
![Page 14: Introduction to Entity Framework Part 2 CRUD Scaffolding Tom Perkins NTPCUG](https://reader036.vdocuments.site/reader036/viewer/2022062321/56649eb45503460f94bbba24/html5/thumbnails/14.jpg)
UPDATE THE ‘CREATE’ PAGE REMOVE ACCESS TO ‘ID’, ADD TRY-CATCH BLOCK
Objective 2
![Page 15: Introduction to Entity Framework Part 2 CRUD Scaffolding Tom Perkins NTPCUG](https://reader036.vdocuments.site/reader036/viewer/2022062321/56649eb45503460f94bbba24/html5/thumbnails/15.jpg)
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 CRUD Scaffolding Tom Perkins NTPCUG](https://reader036.vdocuments.site/reader036/viewer/2022062321/56649eb45503460f94bbba24/html5/thumbnails/16.jpg)
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 CRUD Scaffolding Tom Perkins NTPCUG](https://reader036.vdocuments.site/reader036/viewer/2022062321/56649eb45503460f94bbba24/html5/thumbnails/17.jpg)
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 CRUD Scaffolding Tom Perkins NTPCUG](https://reader036.vdocuments.site/reader036/viewer/2022062321/56649eb45503460f94bbba24/html5/thumbnails/18.jpg)
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 CRUD Scaffolding Tom Perkins NTPCUG](https://reader036.vdocuments.site/reader036/viewer/2022062321/56649eb45503460f94bbba24/html5/thumbnails/19.jpg)
Run, and try to enter Student data with invalid date
![Page 20: Introduction to Entity Framework Part 2 CRUD Scaffolding Tom Perkins NTPCUG](https://reader036.vdocuments.site/reader036/viewer/2022062321/56649eb45503460f94bbba24/html5/thumbnails/20.jpg)
Run with corrected date
![Page 21: Introduction to Entity Framework Part 2 CRUD Scaffolding Tom Perkins NTPCUG](https://reader036.vdocuments.site/reader036/viewer/2022062321/56649eb45503460f94bbba24/html5/thumbnails/21.jpg)
UPDATE THE POSTING OPERATION FOR THE EDIT PAGE
Objective 3
![Page 22: Introduction to Entity Framework Part 2 CRUD Scaffolding Tom Perkins NTPCUG](https://reader036.vdocuments.site/reader036/viewer/2022062321/56649eb45503460f94bbba24/html5/thumbnails/22.jpg)
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 CRUD Scaffolding Tom Perkins NTPCUG](https://reader036.vdocuments.site/reader036/viewer/2022062321/56649eb45503460f94bbba24/html5/thumbnails/23.jpg)
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 CRUD Scaffolding Tom Perkins NTPCUG](https://reader036.vdocuments.site/reader036/viewer/2022062321/56649eb45503460f94bbba24/html5/thumbnails/24.jpg)
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 CRUD Scaffolding Tom Perkins NTPCUG](https://reader036.vdocuments.site/reader036/viewer/2022062321/56649eb45503460f94bbba24/html5/thumbnails/25.jpg)
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 CRUD Scaffolding Tom Perkins NTPCUG](https://reader036.vdocuments.site/reader036/viewer/2022062321/56649eb45503460f94bbba24/html5/thumbnails/26.jpg)
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 CRUD Scaffolding Tom Perkins NTPCUG](https://reader036.vdocuments.site/reader036/viewer/2022062321/56649eb45503460f94bbba24/html5/thumbnails/27.jpg)
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 CRUD Scaffolding Tom Perkins NTPCUG](https://reader036.vdocuments.site/reader036/viewer/2022062321/56649eb45503460f94bbba24/html5/thumbnails/28.jpg)
Edit a Student – Student tab, then Edit hyperlink
![Page 29: Introduction to Entity Framework Part 2 CRUD Scaffolding Tom Perkins NTPCUG](https://reader036.vdocuments.site/reader036/viewer/2022062321/56649eb45503460f94bbba24/html5/thumbnails/29.jpg)
Change the Enrollment Date to 9/1/2011
![Page 30: Introduction to Entity Framework Part 2 CRUD Scaffolding Tom Perkins NTPCUG](https://reader036.vdocuments.site/reader036/viewer/2022062321/56649eb45503460f94bbba24/html5/thumbnails/30.jpg)
UPDATE THE DELETE PAGE - ADD A CUSTOM ERROR MESSAGE WHEN SAVECHANGES() FAILS
Objective 4
![Page 31: Introduction to Entity Framework Part 2 CRUD Scaffolding Tom Perkins NTPCUG](https://reader036.vdocuments.site/reader036/viewer/2022062321/56649eb45503460f94bbba24/html5/thumbnails/31.jpg)
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 CRUD Scaffolding Tom Perkins NTPCUG](https://reader036.vdocuments.site/reader036/viewer/2022062321/56649eb45503460f94bbba24/html5/thumbnails/32.jpg)
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 CRUD Scaffolding Tom Perkins NTPCUG](https://reader036.vdocuments.site/reader036/viewer/2022062321/56649eb45503460f94bbba24/html5/thumbnails/33.jpg)
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 CRUD Scaffolding Tom Perkins NTPCUG](https://reader036.vdocuments.site/reader036/viewer/2022062321/56649eb45503460f94bbba24/html5/thumbnails/34.jpg)
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 CRUD Scaffolding Tom Perkins NTPCUG](https://reader036.vdocuments.site/reader036/viewer/2022062321/56649eb45503460f94bbba24/html5/thumbnails/35.jpg)
Add an Error Message
• Add to \Views\Student\Delete.cshtml
![Page 36: Introduction to Entity Framework Part 2 CRUD Scaffolding Tom Perkins NTPCUG](https://reader036.vdocuments.site/reader036/viewer/2022062321/56649eb45503460f94bbba24/html5/thumbnails/36.jpg)
Delete a Student …
![Page 37: Introduction to Entity Framework Part 2 CRUD Scaffolding Tom Perkins NTPCUG](https://reader036.vdocuments.site/reader036/viewer/2022062321/56649eb45503460f94bbba24/html5/thumbnails/37.jpg)
![Page 38: Introduction to Entity Framework Part 2 CRUD Scaffolding Tom Perkins NTPCUG](https://reader036.vdocuments.site/reader036/viewer/2022062321/56649eb45503460f94bbba24/html5/thumbnails/38.jpg)
Next – Paging, Filtering and Sorting
FINIS