using AircraftPlantContracts.BindingModels; using AircraftPlantContracts.SearchModels; using AircraftPlantContracts.StoragesContracts; using AircraftPlantContracts.ViewModels; using AircraftPlantDatabaseImplement.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AircraftPlantDatabaseImplement.Implements { /// /// Реализация интерфейса хранилища для компонентов /// public class ComponentStorage : IComponentStorage { /// /// Получение полного списка /// /// public List GetFullList() { using var context = new AircraftPlantDatabase(); return context.Components .Select(x => x.GetViewModel) .ToList(); } /// /// Получение фильтрованного списка /// /// /// public List GetFilteredList(ComponentSearchModel model) { if (string.IsNullOrEmpty(model.ComponentName)) { return new(); } using var context = new AircraftPlantDatabase(); return context.Components .Where(x => x.ComponentName.Contains(model.ComponentName)) .Select(x => x.GetViewModel) .ToList(); } /// /// Получение элемента /// /// /// public ComponentViewModel? GetElement(ComponentSearchModel model) { if (string.IsNullOrEmpty(model.ComponentName) && !model.Id.HasValue) { return null; } using var context = new AircraftPlantDatabase(); return context.Components .FirstOrDefault(x => (!string.IsNullOrEmpty(model.ComponentName) && x.ComponentName == model.ComponentName) || (model.Id.HasValue && x.Id == model.Id)) ?.GetViewModel; } /// /// Добавление элемента /// /// /// public ComponentViewModel? Insert(ComponentBindingModel model) { var newComponent = Component.Create(model); if (newComponent == null) { return null; } using var context = new AircraftPlantDatabase(); context.Components.Add(newComponent); context.SaveChanges(); return newComponent.GetViewModel; } /// /// Редактирование элемента /// /// /// public ComponentViewModel? Update(ComponentBindingModel model) { using var context = new AircraftPlantDatabase(); var component = context.Components.FirstOrDefault(x => x.Id == model.Id); if (component == null) { return null; } component.Update(model); context.SaveChanges(); return component.GetViewModel; } /// /// Удаление элемента /// /// /// public ComponentViewModel? Delete(ComponentBindingModel model) { using var context = new AircraftPlantDatabase(); var element = context.Components.FirstOrDefault(rec => rec.Id == model.Id); if (element == null) { return null; } context.Components.Remove(element); context.SaveChanges(); return element.GetViewModel; } } }