SongController.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. using Microsoft.AspNetCore.Mvc;
  2. using Microsoft.EntityFrameworkCore;
  3. using MusicAPI.BaseModel;
  4. using System.Reflection;
  5. namespace MusicAPI.Controllers
  6. {
  7. [Route("api/[controller]")]
  8. [ApiController]
  9. public class SongController : Controller
  10. {
  11. [Route("GetSongs")]
  12. [HttpGet]
  13. public List<Song> GetSongs()
  14. {
  15. using (SongListContext DB = new SongListContext())
  16. {
  17. return DB.Songs.Include("IdArtistNavigation").Include("IdGenreNavigation").ToList();
  18. }
  19. }
  20. [Route("PostSong")]
  21. [HttpPost]
  22. public IActionResult PostSong([FromBody] Song song)
  23. {
  24. if (song == null)
  25. {
  26. return BadRequest("Песня пустая");
  27. }
  28. song.IdSong = default(int);
  29. using (SongListContext DB = new SongListContext())
  30. {
  31. DB.Songs.Add(song);
  32. try
  33. {
  34. DB.SaveChanges();
  35. return Ok();
  36. }
  37. catch (Exception ex)
  38. {
  39. return BadRequest($"{ex.Message}");
  40. }
  41. }
  42. }
  43. [Route("PutSong")]
  44. [HttpPut]
  45. public IActionResult PutProduct([FromBody] Song song)
  46. {
  47. Song? UpdateSong;
  48. using (SongListContext DB = new SongListContext())
  49. {
  50. UpdateSong = DB.Songs.Find(song.IdSong);
  51. if (UpdateSong is null)
  52. {
  53. return BadRequest("Песни нет");
  54. }
  55. UpdateSong.NameSong = song.NameSong;
  56. UpdateSong.Duration = song.Duration;
  57. UpdateSong.IdArtistNavigation = song.IdArtistNavigation;
  58. UpdateSong.IdGenreNavigation = song.IdGenreNavigation;
  59. try
  60. {
  61. DB.SaveChanges();
  62. return Ok();
  63. }
  64. catch (Exception ex)
  65. {
  66. return BadRequest(ex.Message);
  67. }
  68. }
  69. }
  70. [Route("DeleteSong")]
  71. [HttpDelete]
  72. public IActionResult DeleteSong([FromQuery] int id)
  73. {
  74. using (SongListContext DB = new SongListContext())
  75. {
  76. Song song = DB.Songs.Find(id);
  77. if (song is null)
  78. {
  79. return BadRequest("Такой нет");
  80. }
  81. DB.Songs.Remove(song);
  82. try
  83. {
  84. DB.SaveChanges();
  85. return Ok();
  86. }
  87. catch (Exception)
  88. {
  89. return BadRequest("Что то пошло не так");
  90. }
  91. }
  92. }
  93. }
  94. }