using Microsoft.EntityFrameworkCore;
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 ScheduleStorage : IScheduleStorage
{
///
/// Получение полного списка
///
///
public List GetFullList()
{
using var context = new RouteGuideDatabase();
return context.Schedules
.Include(x => x.Route)
.Select(x => x.GetViewModel)
.ToList();
}
///
/// Получение фильтрованного списка
///
///
///
public List GetFilteredList(ScheduleSearchModel model)
{
if (!model.Id.HasValue)
{
return new();
}
using var context = new RouteGuideDatabase();
return context.Schedules
.Include(x => x.Route)
.Where(x => x.Id == model.Id)
.Select(x => x.GetViewModel)
.ToList();
}
///
/// Получение элемента
///
///
///
public ScheduleViewModel? GetElement(ScheduleSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
using var context = new RouteGuideDatabase();
return context.Schedules
.Include(x => x.Route)
.FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id))
?.GetViewModel;
}
///
/// Добавление элемента
///
///
///
public ScheduleViewModel? Insert(ScheduleBindingModel model)
{
using var context = new RouteGuideDatabase();
var newSchedule = Schedule.Create(context, model);
if (newSchedule == null)
{
return null;
}
context.Schedules.Add(newSchedule);
context.SaveChanges();
return newSchedule.GetViewModel;
}
///
/// Редактирование элемента
///
///
///
public ScheduleViewModel? Update(ScheduleBindingModel model)
{
using var context = new RouteGuideDatabase();
var schedule = context.Schedules.FirstOrDefault(x => x.Id == model.Id);
if (schedule == null)
{
return null;
}
schedule.Update(model);
context.SaveChanges();
return schedule.GetViewModel;
}
///
/// Удаление элемента
///
///
///
public ScheduleViewModel? Delete(ScheduleBindingModel model)
{
using var context = new RouteGuideDatabase();
var schedule = context.Schedules.FirstOrDefault(x => x.Id == model.Id);
if (schedule == null)
{
return null;
}
context.Schedules.Remove(schedule);
context.SaveChanges();
return schedule.GetViewModel;
}
}
}