gladyssann

MoviesController.cs

Dec 27th, 2017
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.09 KB | None | 0 0
  1. using AutoMapper;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Web.Http;
  6. using Vidly.Dtos;
  7. using Vidly.Models;
  8.  
  9. namespace Vidly.Controllers.Api
  10. {
  11. public class MoviesController : ApiController
  12. {
  13. private ApplicationDbContext _context;
  14.  
  15. public MoviesController()
  16. {
  17. _context = new ApplicationDbContext();
  18. }
  19.  
  20. public IEnumerable<MoviesDto> GetMovies()
  21. {
  22. return _context.Movies.ToList().Select(Mapper.Map<Movie, MoviesDto>);
  23. }
  24.  
  25. public IHttpActionResult GetMovie(int id)
  26. {
  27. var movie = _context.Movies.SingleOrDefault(c => c.Id == id);
  28.  
  29. if (movie == null)
  30. return NotFound();
  31.  
  32. return Ok(Mapper.Map<Movie, MoviesDto>(movie));
  33. }
  34.  
  35. [HttpPost]
  36. public IHttpActionResult CreateMovie(MoviesDto movieDto)
  37. {
  38. if (!ModelState.IsValid)
  39. return BadRequest();
  40.  
  41. var movie = Mapper.Map<MoviesDto, Movie>(movieDto);
  42. _context.Movies.Add(movie);
  43. _context.SaveChanges();
  44.  
  45. movieDto.Id = movie.Id;
  46. return Created(new Uri(Request.RequestUri + "/" + movie.Id), movieDto);
  47. }
  48.  
  49. [HttpPut]
  50. public IHttpActionResult UpdateMovie(int id, MoviesDto movieDto)
  51. {
  52. if (!ModelState.IsValid)
  53. return BadRequest();
  54.  
  55. var movieInDb = _context.Movies.SingleOrDefault(c => c.Id == id);
  56.  
  57. if (movieInDb == null)
  58. return NotFound();
  59.  
  60. Mapper.Map(movieDto, movieInDb);
  61.  
  62. _context.SaveChanges();
  63.  
  64. return Ok();
  65. }
  66.  
  67. [HttpDelete]
  68. public IHttpActionResult DeleteMovie(int id)
  69. {
  70. var movieInDb = _context.Movies.SingleOrDefault(c => c.Id == id);
  71.  
  72. if (movieInDb == null)
  73. return NotFound();
  74.  
  75. _context.Movies.Remove(movieInDb);
  76. _context.SaveChanges();
  77.  
  78. return Ok();
  79. }
  80. }
  81. }
Add Comment
Please, Sign In to add comment