using Microsoft.EntityFrameworkCore; using PrecastConcretePlantContracts.BindingModels; using PrecastConcretePlantContracts.SearchModels; using PrecastConcretePlantContracts.StoragesContract; using PrecastConcretePlantContracts.ViewModels; using PrecastConcretePlantDatabaseImplement.Models; namespace PrecastConcretePlantDatabaseImplement { public class OrderStorage : IOrderStorage { public OrderViewModel? GetElement(OrderSearchModel model) { using var context = new PrecastConcretePlantDatabase(); if (!model.Id.HasValue) { return null; } return context.Orders.Include(x => x.Reinforced).FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id)?.GetViewModel; } public List GetFilteredList(OrderSearchModel model) { using var context = new PrecastConcretePlantDatabase(); if (!model.Id.HasValue && model.DateFrom.HasValue && model.DateTo.HasValue) { return context.Orders .Where(x => model.DateFrom <= x.DateCreate.Date && x.DateCreate <= model.DateTo).Include(x => x.Reinforced) .Select(x => x.GetViewModel) .ToList(); } var result = GetElement(model); return result != null ? new() { result } : new(); } public List GetFullList() { using var context = new PrecastConcretePlantDatabase(); return context.Orders .Include(x => x.Reinforced) .Select(x => x.GetViewModel) .ToList(); } public OrderViewModel? Insert(OrderBindingModel model) { var newOrder = Order.Create(model); if (newOrder == null) { return null; } using var context = new PrecastConcretePlantDatabase(); context.Orders.Add(newOrder); context.SaveChanges(); return newOrder.GetViewModel; } public OrderViewModel? Update(OrderBindingModel model) { using var context = new PrecastConcretePlantDatabase(); var order = context.Orders.Include(x => x.Reinforced).FirstOrDefault(x => x.Id == model.Id); if (order == null) { return null; } order.Update(model); context.SaveChanges(); return order.GetViewModel; } public OrderViewModel? Delete(OrderBindingModel model) { using var context = new PrecastConcretePlantDatabase(); var element = context.Orders.Include(x => x.Reinforced).FirstOrDefault(x => x.Id == model.Id); if (element != null) { context.Orders.Remove(element); context.SaveChanges(); return element.GetViewModel; } return null; } } }