PIbd-32_Artamonova_T.V._COP_2/UniversityDatabaseImplement/Implements/DirectionStorage.cs

81 lines
2.7 KiB
C#

using UniversityContracts.BindingModels;
using UniversityContracts.SearchModels;
using UniversityContracts.StoragesContracts;
using UniversityContracts.ViewModels;
using UniversityDatabaseImplement.Models;
namespace UniversityDatabaseImplement.Implements
{
public class DirectionStorage : IDirectionStorage
{
public List<DirectionViewModel> GetFullList()
{
using var context = new UniversityDatabase();
return context.Directions
.Select(x => x.GetViewModel)
.ToList();
}
public List<DirectionViewModel> GetFilteredList(DirectionBindingModel model)
{
if (string.IsNullOrEmpty(model.Name))
{
return new();
}
using var context = new UniversityDatabase();
return context.Directions
.Select(x => x.GetViewModel)
.ToList();
}
public DirectionViewModel? GetElement(DirectionBindingModel model)
{
if (string.IsNullOrEmpty(model.Name) && !model.Id.HasValue)
{
return null;
}
using var context = new UniversityDatabase();
return context.Directions
.FirstOrDefault(x => (!string.IsNullOrEmpty(model.Name) &&
x.Name == model.Name) ||
(model.Id.HasValue && x.Id == model.Id))
?.GetViewModel;
}
public DirectionViewModel? Insert(DirectionBindingModel model)
{
using var context = new UniversityDatabase();
var newDirection = Direction.Create(model);
if (newDirection == null)
{
return null;
}
context.Directions.Add(newDirection);
context.SaveChanges();
return newDirection.GetViewModel;
}
public DirectionViewModel? Update(DirectionBindingModel model)
{
using var context = new UniversityDatabase();
var direction = context.Directions.FirstOrDefault(rec => rec.Id == model.Id);
if (direction == null)
{
return null;
}
direction.Update(model);
context.SaveChanges();
return direction.GetViewModel;
}
public DirectionViewModel? Delete(DirectionBindingModel model)
{
using var context = new UniversityDatabase();
var element = context.Directions
.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Directions.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}