SUBD/Sushi/SushiDatabaseImplement/Implement/EmployeeStorage.cs

77 lines
2.6 KiB
C#

using SushiContracts.BindingModels;
using SushiContracts.SearchModels;
using SushiContracts.StorageContracts;
using SushiContracts.ViewModels;
using SushiDatabaseImplement.Models;
namespace SushiDatabaseImplement.Implements
{
public class EmployeeStorage : IEmployeeStorage
{
public List<EmployeeViewModel> GetFullList()
{
using var context = new SushiDatabase();
return context.Employees.Select(x => x.GetViewModel).ToList();
}
public List<EmployeeViewModel> GetFilteredList(EmployeeSearchModel model)
{
if (string.IsNullOrEmpty(model.EmployeeName))
{
return new();
}
using var context = new SushiDatabase();
return context.Employees.Where(x => x.EmployeeName.Contains(model.EmployeeName)).Select(x => x.GetViewModel).ToList();
}
public EmployeeViewModel? GetElement(EmployeeSearchModel model)
{
if (string.IsNullOrEmpty(model.EmployeeName) && !model.Id.HasValue)
{
return null;
}
using var context = new SushiDatabase();
return context.Employees.FirstOrDefault(x => (!string.IsNullOrEmpty(model.EmployeeName) && x.EmployeeName == model.EmployeeName) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
}
public EmployeeViewModel? Insert(EmployeeBindingModel model)
{
var newEmployee = Employee.Create(model);
if (newEmployee == null)
{
return null;
}
using var context = new SushiDatabase();
context.Employees.Add(newEmployee);
context.SaveChanges();
return newEmployee.GetViewModel;
}
public EmployeeViewModel? Update(EmployeeBindingModel model)
{
using var context = new SushiDatabase();
var client = context.Employees.FirstOrDefault(x => x.Id == model.Id);
if (client == null)
{
return null;
}
client.Update(model);
context.SaveChanges();
return client.GetViewModel;
}
public EmployeeViewModel? Delete(EmployeeBindingModel model)
{
using var context = new SushiDatabase();
var element = context.Employees.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Employees.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}