using RouteGuideContracts.BindingModels; using RouteGuideContracts.SearchModels; using RouteGuideContracts.StoragesContracts; using RouteGuideContracts.ViewModels; using RouteGuideDatabaseImplement.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RouteGuideDatabaseImplement.Implements { /// /// Хранилище для сущности "Остановка" /// public class StopStorage : IStopStorage { /// /// Получение полного списка /// /// public List GetFullList() { using var context = new RouteGuideDatabase(); return context.Stops .Select(x => x.GetViewModel) .ToList(); } /// /// Получение фильтрованного списка /// /// /// public List GetFilteredList(StopSearchModel model) { if (string.IsNullOrEmpty(model.Name)) { return new(); } using var context = new RouteGuideDatabase(); return context.Stops .Where(x => x.Name.Contains(model.Name)) .Select(x => x.GetViewModel) .ToList(); } /// /// Получение элемента /// /// /// public StopViewModel? GetElement(StopSearchModel model) { if (!model.Id.HasValue && string.IsNullOrEmpty(model.Name)) { return null; } using var context = new RouteGuideDatabase(); return context.Stops .FirstOrDefault(x => (!string.IsNullOrEmpty(model.Name) && x.Name.Contains(model.Name)) || (model.Id.HasValue && x.Id == model.Id)) ?.GetViewModel; } /// /// Добавление элемента /// /// /// public StopViewModel? Insert(StopBindingModel model) { var newStop = Stop.Create(model); if (newStop == null) { return null; } using var context = new RouteGuideDatabase(); context.Stops.Add(newStop); context.SaveChanges(); return newStop.GetViewModel; } /// /// Редактирование элемента /// /// /// public StopViewModel? Update(StopBindingModel model) { using var context = new RouteGuideDatabase(); var stop = context.Stops.FirstOrDefault(x => x.Id == model.Id); if (stop == null) { return null; } stop.Update(model); context.SaveChanges(); return stop.GetViewModel; } /// /// Удаление элемента /// /// /// public StopViewModel? Delete(StopBindingModel model) { using var context = new RouteGuideDatabase(); var stop = context.Stops.FirstOrDefault(x => x.Id == model.Id); if (stop == null) { return null; } context.Stops.Remove(stop); context.SaveChanges(); return stop.GetViewModel; } } }