Exactly 1 month and 5 days after the first video tutorial for the ASP.NET MVC with EF Core series, the last 10th video tutorial, following the Microsoft ones, is published. It is about advanced scenarios, and I have mentioned the following points in it:
- Perform raw SQL queries
- Call a query to return entities
- Call a query to return other types
- Call an update query
- Examine SQL queries
Interesting part is calling an update query, which shows with minimal code, once again how to add a view and controller to our application:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public IActionResult UpdateCourseCredits() { return View(); } [HttpPost] public async Task<IActionResult> UpdateCourseCredits(int? multiplier) { if (multiplier!=null) { ViewData["RowsAffected"] = await _context.Database.ExecuteSqlCommandAsync( "UPDATE Cursos SET Credits = Credits * {0}", parameters: multiplier); } return View(); } |
And the View():
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
@{ ViewBag.Title = "UpdateCourseCredits"; } <h2>Update Course Credits</h2> @if (ViewData["RowsAffected"] == null) { <form asp-action="UpdateCourseCredits"> <div class="form-actions no-color"> <p> Enter a number to multiply the credits by: @Html.TextBox("multiplier") </p> <p> <input type ="submit" value="Update" class="btn btn-default" /> </p> </div> </form> } @if (ViewData["RowsAffected"] != null) { <p> Number of rows updated: @ViewData["RowsAffected"] </p> } <div> @Html.ActionLink("Back to List", "Index") </div> |
Last (and probably least) is the line for adding the ActionLink to the Index.cshtml of the Views>Courses:
@Html.ActionLink("Update Course Credits", "UpdateCourseCredits","Courses")
The whole code is available in GitHub!
Enjoy it!