| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118 |
- using DutchTreat.Data.Entities;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.EntityFrameworkCore;
- using Microsoft.Extensions.Logging;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace DutchTreat.Data
- {
- public class DutchRepository : IDutchRepository
- {
- private readonly DutchContext _ctx;
- private readonly ILogger<DutchRepository> _logger;
- public DutchRepository(DutchContext ctx, ILogger<DutchRepository> logger)
- {
- _ctx = ctx;
- _logger = logger;
- }
- public void AddEntity(Order model)
- {
- _ctx.Add(model);
- }
- public IEnumerable<Order> GetAllOrders(bool includedItems)
- {
- try
- {
- if (includedItems)
- {
- _logger.LogInformation("GetAllOrders was called");
- return _ctx.Orders
- .Include(o => o.Items)
- .ThenInclude(i => i.Product)
- .ToList();
- }
- else
- {
- return _ctx.Orders.ToList();
- }
- }
- catch (Exception ex)
- {
- _logger.LogError($"Failed to get all orders: {ex}");
- return null;
- }
- }
- public IEnumerable<Order> GetAllOrdersByUser(string username, bool includedItems)
- {
- try
- {
- if (includedItems)
- {
- _logger.LogInformation("GetAllOrdersByUser was called");
- return _ctx.Orders
- .Where(o => o.User.UserName == username)
- .Include(o => o.Items)
- .ThenInclude(i => i.Product)
- .ToList();
- }
- else
- {
- return _ctx.Orders
- .Where(o => o.User.UserName == username)
- .ToList();
- }
- }
- catch (Exception ex)
- {
- _logger.LogError($"Failed to get all orders: {ex}");
- return null;
- }
- }
- public IEnumerable<Product> GetAllProducts()
- {
- try
- {
- _logger.LogInformation("GetAllProduct was called");
- return _ctx.Products
- .OrderBy(p => p.Title)
- .ToList();
- }
- catch (Exception ex)
- {
- _logger.LogError($"Failed to get all products: {ex}");
- return null;
- }
- }
- public Order GetOrderById(string username, int id)
- {
- return _ctx.Orders
- .Include(o => o.Items)
- .ThenInclude(i => i.Product)
- .Where(o => o.Id == id && o.User.UserName == username)
- .FirstOrDefault();
- }
- public IEnumerable<Product> GetProductsByCategory(string category)
- {
- return _ctx.Products
- .Where(p => p.Category == category)
- .ToList();
- }
- public bool SaveAll()
- {
- return _ctx.SaveChanges() > 0;
- }
- }
- }
|