using Microsoft.EntityFrameworkCore; using SushiBarContracts.BindingModels; using SushiBarContracts.SearchModels; using SushiBarContracts.StoragesContracts; using SushiBarContracts.ViewModels; using SushiBarDatabaseImplement.Models; namespace SushiBarDatabaseImplement.Implements { public class OrderStorage : IOrderStorage { public OrderViewModel? Delete(OrderBindingModel model) { using var context = new SushiBarDatabase(); var element = context.Orders .Include(x => x.Sushi) .FirstOrDefault(rec => rec.Id == model.Id); if (element != null) { context.Orders.Remove(element); context.SaveChanges(); return element.GetViewModel; } return null; } public OrderViewModel? GetElement(OrderSearchModel model) { if (!model.Id.HasValue) { return null; } using var context = new SushiBarDatabase(); return context.Orders .Include(x => x.Sushi).Include(x => x.Client) .FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id) ?.GetViewModel; } public List GetFilteredList(OrderSearchModel model) { using var context = new SushiBarDatabase(); if ((!model.DateFrom.HasValue || !model.DateTo.HasValue) && !model.ClientId.HasValue && !model.Status.HasValue) { return new(); } return context.Orders.Include(x => x.Sushi).Include(x => x.Client).Include(x => x.Implementer).Where(x => (model.DateFrom.HasValue && model.DateTo.HasValue && x.DateCreate >= model.DateFrom && x.DateCreate <= model.DateTo) || (model.ClientId.HasValue && x.ClientId == model.ClientId) || (model.Status.HasValue && x.Status == model.Status)) .Select(x => x.GetViewModel).ToList(); } public List GetFullList() { using var context = new SushiBarDatabase(); return context.Orders.Include(x => x.Sushi).Include(x => x.Client).Include(y => y.Implementer).Select(x => x.GetViewModel).ToList(); } public OrderViewModel? Insert(OrderBindingModel model) { using var context = new SushiBarDatabase(); if (model == null) return null; var newOrder = Order.Create(context, model); if (newOrder == null) { return null; } context.Orders.Add(newOrder); context.SaveChanges(); return 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(context, model); context.SaveChanges(); return order.GetViewModel; } } }