CourseWorkElectronicsShop/ElectronicsShop/ElectronicsShopDataBaseImplement/Implements/EmployeeStorage.cs

80 lines
2.6 KiB
C#

using ElectronicsShopContracts.BindingModels;
using ElectronicsShopContracts.SearchModels;
using ElectronicsShopContracts.StorageContracts;
using ElectronicsShopContracts.ViewModels;
using ElectronicsShopDataBaseImplement.Models;
namespace ElectronicsShopDataBaseImplement.Implements
{
public class EmployeeStorage : IEmployeeStorage
{
public EmployeeViewModel? Delete(EmployeeBindingModel model)
{
using var context = new Database();
var element = context.Employees.FirstOrDefault(rec => rec.ID == model.ID);
if (element != null)
{
context.Employees.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
public EmployeeViewModel? GetElement(EmployeeSearchModel model)
{
if (string.IsNullOrEmpty(model.Login) && !model.ID.HasValue)
{
return null;
}
using var context = new Database();
return context.Employees.FirstOrDefault(x =>
(!string.IsNullOrEmpty(model.Login) && x.EmployeeFIO == model.EmployeFIO ||
(model.ID.HasValue && x.ID == model.ID)))?.GetViewModel;
}
public List<EmployeeViewModel> GetFilteredList(EmployeeSearchModel model)
{
if (string.IsNullOrEmpty(model.Login))
{
return new();
}
using var context = new Database();
return context.Employees.Where(x => x.Login.Contains(model.Login)).Select(x => x.GetViewModel).ToList();
}
public List<EmployeeViewModel> GetFullList()
{
using var context = new Database();
return context.Employees.Select(x => x.GetViewModel).ToList();
}
public EmployeeViewModel? Insert(EmployeeBindingModel model)
{
var newComponent = Employee.Create(model);
if (newComponent == null)
{
return null;
}
using var context = new Database();
context.Employees.Add(newComponent);
context.SaveChanges();
return newComponent.GetViewModel;
}
public EmployeeViewModel? Update(EmployeeBindingModel model)
{
using var context = new Database();
var component = context.Employees.FirstOrDefault(x => x.ID == model.ID);
if (component == null)
{
return null;
}
component.Update(model);
context.SaveChanges();
return component.GetViewModel;
}
}
}