forked from simplefx/Simple.OData
-
Notifications
You must be signed in to change notification settings - Fork 198
Expand file tree
/
Copy pathMoviesController.cs
More file actions
118 lines (98 loc) · 2.33 KB
/
MoviesController.cs
File metadata and controls
118 lines (98 loc) · 2.33 KB
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
using Microsoft.AspNetCore.OData;
using Microsoft.AspNetCore.OData.Routing;
using Microsoft.AspNetCore.OData;
using Microsoft.AspNetCore.OData.Routing;
using WebApiOData.V4.Samples.Models;
using Microsoft.AspNetCore.OData.Routing.Controllers;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.OData.Formatter;
namespace WebApiOData.V4.Samples.Controllers;
public class MoviesController : ODataController
{
private readonly MoviesContext _db = new();
public IActionResult Get()
{
return Ok(_db.Movies);
}
[HttpPost]
public IActionResult CheckOut(int key)
{
var movie = _db.Movies.FirstOrDefault(m => m.ID == key);
if (movie is null)
{
return BadRequest(ModelState);
}
if (!TryCheckoutMovie(movie))
{
return BadRequest("The movie is already checked out.");
}
return Ok(movie);
}
[HttpPost]
public IActionResult Return(int key)
{
var movie = _db.Movies.FirstOrDefault(m => m.ID == key);
if (movie is null)
{
return BadRequest(ModelState);
}
movie.DueDate = null;
return Ok(movie);
}
// Check out a list of movies.
[HttpPost]
public IActionResult CheckOutMany(ODataActionParameters parameters)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
// Client passes a list of movie IDs to check out.
var movieIDs = new HashSet<int>(parameters["MovieIDs"] as IEnumerable<int>);
// Try to check out each movie in the list.
var results = new List<Movie>();
foreach (var movie in _db.Movies.Where(m => movieIDs.Contains(m.ID)))
{
if (TryCheckoutMovie(movie))
{
results.Add(movie);
}
}
// Return a list of the movies that were checked out.
return Ok(results);
}
[HttpPost]
[ODataRoute("CreateMovie")]
public IActionResult CreateMovie(ODataActionParameters parameters)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var title = parameters["Title"] as string;
var movie = new Movie()
{
Title = title,
ID = _db.Movies.Count + 1,
};
_db.Movies.Add(movie);
return Created(movie);
}
protected Movie GetMovieByKey(int key)
{
return _db.Movies.FirstOrDefault(m => m.ID == key);
}
private static bool TryCheckoutMovie(Movie movie)
{
if (movie.IsCheckedOut)
{
return false;
}
else
{
// To check out a movie, set the due date.
movie.DueDate = DateTime.Now.AddDays(7);
return true;
}
}
}