PIbd-22_Bondarenko_M.S_SUBD/PersonnelDepartmentView/PersonnelDepartmentDatabaseImplement/Implements/PositionStorage.cs

86 lines
2.3 KiB
C#

using PersonnelDepartmentContracts.BindingModels;
using PersonnelDepartmentContracts.SearchModels;
using PersonnelDepartmentContracts.StoragesContracts;
using PersonnelDepartmentContracts.ViewModels;
using PersonnelDepartmentDatabaseImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PersonnelDepartmentDatabaseImplement.Implements
{
public class PositionStorage : IPositionStorage
{
public PositionViewModel? Delete(PositionBindingModel model)
{
using var context = new PersonnelDepartmentDatabase();
var element = context.Positions
.FirstOrDefault(x => x.Id == model.Id);
if (element == null)
{
return null;
}
context.Positions.Remove(element);
return element.GetViewModel;
}
public PositionViewModel? GetElement(PositionSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
using var context = new PersonnelDepartmentDatabase();
return context.Positions
.FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id) ||
(!string.IsNullOrEmpty(model.Name) && x.Name == model.Name))?.GetViewModel;
}
public List<PositionViewModel> GetFilteredList(PositionSearchModel model)
{
using var context = new PersonnelDepartmentDatabase();
return context.Positions
.Where(x => (model.Id.HasValue && x.Id == model.Id) ||
(!string.IsNullOrEmpty(model.Name) && x.Name == model.Name))
.Select(x => x.GetViewModel).ToList();
}
public List<PositionViewModel> GetFullList()
{
using var context = new PersonnelDepartmentDatabase();
return context.Positions
.Select(x => x.GetViewModel)
.ToList();
}
public PositionViewModel? Insert(PositionBindingModel model)
{
var newElement = Position.Create(model);
if (newElement == null)
{
return null;
}
using var context = new PersonnelDepartmentDatabase();
context.Positions.Add(newElement);
context.SaveChanges();
return newElement.GetViewModel;
}
public PositionViewModel? Update(PositionBindingModel model)
{
using var context = new PersonnelDepartmentDatabase();
var element = context.Positions
.FirstOrDefault(x => x.Id == model.Id);
if (element == null)
{
return null;
}
element.Update(model);
context.SaveChanges();
return element.GetViewModel;
}
}
}