using SushiBarContracts.BindingModel; using SushiBarContracts.SearchModel; using SushiBarContracts.StoragesContracts; using SushiBarContracts.ViewModels; using SushiBarDatabaseImplement.Models; namespace SushiBarDatabaseImplement.Implements { public class OrderStorage : IOrderStorage { public List GetFullList() { using var context = new SushiBarDatabase(); return context.Orders.Select(x => AccessViewModel(x.GetViewModel)).ToList(); } public List GetFilteredList(OrderSearchModel model) { if (!model.Id.HasValue && !model.DateTo.HasValue && !model.DateFrom.HasValue) { return new(); } using var context = new SushiBarDatabase(); if (model.Id.HasValue) return context.Orders.Where(x => x.Id == model.Id).Select(x => AccessViewModel(x.GetViewModel)).ToList(); else return context.Orders.Where(x => x.DateCreate >= model.DateFrom).Where(x => x.DateCreate <= model.DateTo).Select(x => AccessViewModel(x.GetViewModel)).ToList(); } public OrderViewModel? GetElement(OrderSearchModel model) { if (!model.Id.HasValue) { return null; } using var context = new SushiBarDatabase(); return AccessViewModel(context.Orders.FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id).GetViewModel); } public OrderViewModel? Insert(OrderBindingModel model) { using var context = new SushiBarDatabase(); var newOrder = Order.Create(model); if (newOrder == null) { return null; } context.Orders.Add(newOrder); context.SaveChanges(); return AccessViewModel(newOrder.GetViewModel); } public OrderViewModel? Update(OrderBindingModel model) { using var context = new SushiBarDatabase(); var order = context.Orders.FirstOrDefault(x => x.Id == model.Id); if (order == null) { return null; } order.Update(model); context.SaveChanges(); return AccessViewModel(order.GetViewModel); } public OrderViewModel? Delete(OrderBindingModel model) { using var context = new SushiBarDatabase(); var order = context.Orders.FirstOrDefault(x => x.Id == model.Id); if (order == null) return null; context.Remove(order); context.SaveChanges(); return AccessViewModel(order.GetViewModel); } public static OrderViewModel? AccessViewModel(OrderViewModel viewModel) { using var context = new SushiBarDatabase(); var sushi = context.Sushis.FirstOrDefault(x => x.Id == viewModel.SushiId); if (viewModel != null) { viewModel.SushiName = sushi!.SushiName; return viewModel; } return null; } } }