forked from davidfowl/Todos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTodoController.cs
61 lines (53 loc) · 1.44 KB
/
TodoController.cs
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
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Routing;
using Microsoft.EntityFrameworkCore;
namespace Todos
{
[ApiController]
[Route("/api/todos")]
public class TodoController : ControllerBase
{
private readonly TodoDbContext _db;
public TodoController(TodoDbContext db)
{
_db = db ?? throw new ArgumentNullException(nameof(db));
}
[HttpGet]
public async Task<ActionResult<List<Todo>>> GetAll()
{
var todos = await _db.Todos.ToListAsync();
return todos;
}
[HttpGet("{id}")]
public async Task<ActionResult<Todo>> Get(long id)
{
var todo = await _db.Todos.FindAsync(id);
if (todo == null)
{
return NotFound();
}
return todo;
}
[HttpPost]
public async Task Post(Todo todo)
{
_db.Todos.Add(todo);
await _db.SaveChangesAsync();
}
[HttpDelete("{id}")]
public async Task<IActionResult> Delete(long id)
{
var todo = await _db.Todos.FindAsync(id);
if (todo == null)
{
return NotFound();
}
_db.Todos.Remove(todo);
await _db.SaveChangesAsync();
return Ok();
}
}
}