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…
Web API with Visual Studio 2019 is quite a bolierplate task – it is doable in less than 45 minutes, following the Microsoft.com tutorial: The video tutorial is here: The TodoController , implementing the CRUD actions looks like this:
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 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 |
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using TodoApi.Models; namespace TodoApi.Controllers { [ApiController] [Route("api/[controller]")] public class TodoController : Controller { private readonly TodoContext _context; public TodoController(TodoContext context) { _context = context; if (_context.TodoItems.Count() == 0) { _context.TodoItems.Add(new TodoItem { Name = "Learn VBA" }); _context.SaveChanges(); } } //GET: api/Todo [HttpGet] public async Task<ActionResult<IEnumerable<TodoItem>>> GetTodoItems() { return await _context.TodoItems.ToListAsync(); } //GET: api/Todo/3 [HttpGet("{id}")] public async Task<ActionResult<TodoItem>> GetTodoItem(long id) { var todoItem = await _context.TodoItems.FindAsync(id); if (todoItem== null) { return NotFound(); } return todoItem; } //POST: api/Todo [HttpPost] public async Task<ActionResult<TodoItem>> PostTodoItem(TodoItem item) { _context.TodoItems.Add(item); await _context.SaveChangesAsync(); return CreatedAtAction(nameof(GetTodoItem), new { id = item.Id }, item); } //PUT: api/Todo/3 [HttpPut("{id}")] public async Task<IActionResult> PutTodoItem(long id, TodoItem item) { if (id!=item.Id) { return BadRequest(); } _context.Entry(item).State = EntityState.Modified; await _context.SaveChangesAsync(); return NoContent(); } //DELETE: api/Todo/3 [HttpDelete("{id}")] public async Task<IActionResult> DeleteTodoItem(long id) { var todoItem = await _context.TodoItems.FindAsync(id); if (todoItem == null) { return NotFound(); } _context.TodoItems.Remove(todoItem); await _context.SaveChangesAsync(); return NoContent(); } } } |
The…