You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

UserController.cs 1.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using Microsoft.AspNetCore.Mvc;
  2. using ProRestaurant.Models.Accounts;
  3. using ProRestaurant.Repository.Accounts;
  4. using System.Transactions;
  5. namespace ProRestaurant.Controllers.Accounts
  6. {
  7. [Route("api/[controller]")]
  8. [ApiController]
  9. public class UserController : ControllerBase
  10. {
  11. private readonly IUserRepository userRepository;
  12. public UserController(IUserRepository userRepo)
  13. {
  14. userRepository = userRepo;
  15. }
  16. [HttpGet]
  17. public IActionResult Get()
  18. {
  19. return new OkObjectResult(userRepository.GetUsers());
  20. }
  21. [HttpGet("{id}")]
  22. public IActionResult Get(int id)
  23. {
  24. var user = userRepository.GetUser(u => u.Id == id);
  25. return new OkObjectResult(user);
  26. }
  27. [HttpPost]
  28. public IActionResult Post([FromBody] User user)
  29. {
  30. using (var scope = new TransactionScope())
  31. {
  32. userRepository.Insert(user);
  33. scope.Complete();
  34. return CreatedAtAction(nameof(Get), new { id = user.Id }, user);
  35. }
  36. }
  37. [HttpPut]
  38. public IActionResult Put([FromBody] User user)
  39. {
  40. if (user != null)
  41. {
  42. using (var scope = new TransactionScope())
  43. {
  44. userRepository.Update(user);
  45. scope.Complete();
  46. return new OkResult();
  47. }
  48. }
  49. return new NoContentResult();
  50. }
  51. [HttpDelete("{id}")]
  52. public IActionResult Delete(int id)
  53. {
  54. userRepository.Remove(userRepository.GetUser(u => u.Id == id));
  55. return new OkResult();
  56. }
  57. }
  58. }