DutchRepository.cs 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. using DutchTreat.Data.Entities;
  2. using Microsoft.AspNetCore.Mvc;
  3. using Microsoft.EntityFrameworkCore;
  4. using Microsoft.Extensions.Logging;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. namespace DutchTreat.Data
  11. {
  12. public class DutchRepository : IDutchRepository
  13. {
  14. private readonly DutchContext _ctx;
  15. private readonly ILogger<DutchRepository> _logger;
  16. public DutchRepository(DutchContext ctx, ILogger<DutchRepository> logger)
  17. {
  18. _ctx = ctx;
  19. _logger = logger;
  20. }
  21. public void AddEntity(Order model)
  22. {
  23. _ctx.Add(model);
  24. }
  25. public IEnumerable<Order> GetAllOrders(bool includedItems)
  26. {
  27. try
  28. {
  29. if (includedItems)
  30. {
  31. _logger.LogInformation("GetAllOrders was called");
  32. return _ctx.Orders
  33. .Include(o => o.Items)
  34. .ThenInclude(i => i.Product)
  35. .ToList();
  36. }
  37. else
  38. {
  39. return _ctx.Orders.ToList();
  40. }
  41. }
  42. catch (Exception ex)
  43. {
  44. _logger.LogError($"Failed to get all orders: {ex}");
  45. return null;
  46. }
  47. }
  48. public IEnumerable<Order> GetAllOrdersByUser(string username, bool includedItems)
  49. {
  50. try
  51. {
  52. if (includedItems)
  53. {
  54. _logger.LogInformation("GetAllOrdersByUser was called");
  55. return _ctx.Orders
  56. .Where(o => o.User.UserName == username)
  57. .Include(o => o.Items)
  58. .ThenInclude(i => i.Product)
  59. .ToList();
  60. }
  61. else
  62. {
  63. return _ctx.Orders
  64. .Where(o => o.User.UserName == username)
  65. .ToList();
  66. }
  67. }
  68. catch (Exception ex)
  69. {
  70. _logger.LogError($"Failed to get all orders: {ex}");
  71. return null;
  72. }
  73. }
  74. public IEnumerable<Product> GetAllProducts()
  75. {
  76. try
  77. {
  78. _logger.LogInformation("GetAllProduct was called");
  79. return _ctx.Products
  80. .OrderBy(p => p.Title)
  81. .ToList();
  82. }
  83. catch (Exception ex)
  84. {
  85. _logger.LogError($"Failed to get all products: {ex}");
  86. return null;
  87. }
  88. }
  89. public Order GetOrderById(string username, int id)
  90. {
  91. return _ctx.Orders
  92. .Include(o => o.Items)
  93. .ThenInclude(i => i.Product)
  94. .Where(o => o.Id == id && o.User.UserName == username)
  95. .FirstOrDefault();
  96. }
  97. public IEnumerable<Product> GetProductsByCategory(string category)
  98. {
  99. return _ctx.Products
  100. .Where(p => p.Category == category)
  101. .ToList();
  102. }
  103. public bool SaveAll()
  104. {
  105. return _ctx.SaveChanges() > 0;
  106. }
  107. }
  108. }