using AircraftPlantContracts.BindingModels;
using AircraftPlantContracts.SearchModels;
using AircraftPlantContracts.StoragesContracts;
using AircraftPlantContracts.ViewModels;
using AircraftPlantDatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AircraftPlantDatabaseImplement.Implements
{
///
/// Реализация интерфейса хранилища для изделий
///
public class PlaneStorage : IPlaneStorage
{
///
/// Получение полного списка
///
///
public List GetFullList()
{
using var context = new AircraftPlantDatabase();
return context.Planes
.Include(x => x.Components)
.ThenInclude(x => x.Component)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
///
/// Получение фильтрованного списка
///
///
///
public List GetFilteredList(PlaneSearchModel model)
{
if (string.IsNullOrEmpty(model.PlaneName))
{
return new();
}
using var context = new AircraftPlantDatabase();
return context.Planes
.Include(x => x.Components)
.ThenInclude(x => x.Component)
.Where(x => x.PlaneName.Contains(model.PlaneName))
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
///
/// Получение элемента
///
///
///
public PlaneViewModel? GetElement(PlaneSearchModel model)
{
if (string.IsNullOrEmpty(model.PlaneName) && !model.Id.HasValue)
{
return null;
}
using var context = new AircraftPlantDatabase();
return context.Planes
.Include(x => x.Components)
.ThenInclude(x => x.Component)
.FirstOrDefault(x => (!string.IsNullOrEmpty(model.PlaneName) &&
x.PlaneName == model.PlaneName) ||
(model.Id.HasValue && x.Id == model.Id))
?.GetViewModel;
}
///
/// Добавление элемента
///
///
///
public PlaneViewModel? Insert(PlaneBindingModel model)
{
using var context = new AircraftPlantDatabase();
var newPlane = Plane.Create(context, model);
if (newPlane == null)
{
return null;
}
context.Planes.Add(newPlane);
context.SaveChanges();
return newPlane.GetViewModel;
}
///
/// Редактирование элемента
///
///
///
public PlaneViewModel? Update(PlaneBindingModel model)
{
using var context = new AircraftPlantDatabase();
using var transaction = context.Database.BeginTransaction();
try
{
var plane = context.Planes.FirstOrDefault(rec => rec.Id == model.Id);
if (plane == null)
{
return null;
}
plane.Update(model);
context.SaveChanges();
plane.UpdateComponents(context, model);
transaction.Commit();
return plane.GetViewModel;
}
catch
{
transaction.Rollback();
throw;
}
}
///
/// Удаление элемента
///
///
///
public PlaneViewModel? Delete(PlaneBindingModel model)
{
using var context = new AircraftPlantDatabase();
var element = context.Planes
.Include(x => x.Components)
.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Planes.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}