using ComputerShopContracts.BindingModels; using ComputerShopContracts.SearchModels; using ComputerShopContracts.StorageContracts; using ComputerShopContracts.ViewModels; using ComputerShopDatabaseImplement.Models; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ComputerShopDatabaseImplement.Implements { public class PurchaseStorage : IPurchaseStorage { public PurchaseViewModel? GetElement(PurchaseSearchModel model) { if (!model.Id.HasValue) { return null; } using var context = new ComputerShopDatabase(); return context.Purchases.Include(x => x.Component) .FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id)) ?.GetViewModel; } public List GetFilteredList(PurchaseSearchModel model) { if (!model.Id.HasValue && !model.DateFrom.HasValue && !model.DateTo.HasValue && !model.ClientId.HasValue && !model.DateFrom.HasValue && !model.DateTo.HasValue) { return new(); } using var context = new ComputerShopDatabase(); if (model.DateFrom.HasValue && model.DateTo.HasValue) return context.Purchases .Include(x => x.Component) .Where(x => x.DateCreate >= model.DateFrom && x.DateCreate <= model.DateTo) .Select(x => x.GetViewModel) .ToList(); if (model.ClientId.HasValue) { return context.Purchases .Include(x => x.Client) .Where(x => x.ClientId == model.ClientId) .Select(x => x.GetViewModel) .ToList(); } return context.Purchases .Where(x => x.Id == model.Id) .Include(x => x.Component) .Select(x => x.GetViewModel) .ToList(); } public List GetFullList() { using var context = new ComputerShopDatabase(); return context.Purchases.Include(x => x.Component).Select(x => x.GetViewModel).ToList(); } public PurchaseViewModel? Insert(PurchaseBindingModel model) { var newOrder = Purchase.Create(model); if (newOrder == null) { return null; } using var context = new ComputerShopDatabase(); context.Purchases.Add(newOrder); context.SaveChanges(); return context.Purchases.Include(x => x.Component).FirstOrDefault(x => x.Id == newOrder.Id)?.GetViewModel; } public PurchaseViewModel? Update(PurchaseBindingModel model) { using var context = new ComputerShopDatabase(); var order = context.Purchases.FirstOrDefault(x => x.Id == model.Id); if (order == null) { return null; } order.Update(model); context.SaveChanges(); return context.Purchases.Include(x => x.Component).FirstOrDefault(x => x.Id == model.Id)?.GetViewModel; } public PurchaseViewModel? Delete(PurchaseBindingModel model) { using var context = new ComputerShopDatabase(); var element = context.Purchases.FirstOrDefault(rec => rec.Id == model.Id); if (element != null) { context.Purchases.Remove(element); context.SaveChanges(); return element.GetViewModel; } return null; } } }