using ComputerHardwareStoreContracts.BindingModels; using ComputerHardwareStoreContracts.SearchModels; using ComputerHardwareStoreContracts.StorageContracts; using ComputerHardwareStoreContracts.ViewModels; using ComputerHardwareStoreDatabaseImplement.Models; namespace ComputerHardwareStoreDatabaseImplement.Implements { public class ComponentStorage : IComponentStorage { public List GetFullList() { using var context = new ComputerHardwareStoreDBContext(); return context.Components .Select(c => c.GetViewModel) .ToList(); } public List GetFilteredList(ComponentSearchModel model) { if (string.IsNullOrEmpty(model.Name)) { return new(); } using var context = new ComputerHardwareStoreDBContext(); return context.Components .Where(c => c.Name.Contains(model.Name)) .Select(c => c.GetViewModel) .ToList(); } public ComponentViewModel? GetElement(ComponentSearchModel model) { if (string.IsNullOrEmpty(model.Name) && !model.Id.HasValue) { return null; } using var context = new ComputerHardwareStoreDBContext(); return context.Components .FirstOrDefault(c => (!string.IsNullOrEmpty(model.Name) && c .Name == model.Name) || (model.Id.HasValue && c.Id == model.Id)) ?.GetViewModel; } public ComponentViewModel? Insert(ComponentBindingModel model) { using var context = new ComputerHardwareStoreDBContext(); var newComponent = Component.Create(context, model); if (newComponent == null) { return null; } context.Components.Add(newComponent); context.SaveChanges(); return newComponent.GetViewModel; } public ComponentViewModel? Update(ComponentBindingModel model) { using var context = new ComputerHardwareStoreDBContext(); var element = context.Components.FirstOrDefault(x => x.Id == model.Id); if (element == null) { return null; } element.Update(model); context.SaveChanges(); return element.GetViewModel; } public ComponentViewModel? Delete(ComponentBindingModel model) { using var context = new ComputerHardwareStoreDBContext(); var element = context.Components.FirstOrDefault(c => c.Id == model.Id); if (element == null) { return null; } context.Components.Remove(element); context.SaveChanges(); return element.GetViewModel; } } }