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 EmployeeStorage : IEmployeeStorage { public EmployeeViewModel? Delete(EmployeeBindingModel model) { using var context = new PersonnelDepartmentDatabase(); var element = context.Employees .FirstOrDefault(x => x.Id == model.Id); if (element == null) { return null; } context.Employees.Remove(element); return element.GetViewModel; } public EmployeeViewModel? GetElement(EmployeeSearchModel model) { if (!model.Id.HasValue) { return null; } using var context = new PersonnelDepartmentDatabase(); return context.Employees .FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id) || (!string.IsNullOrEmpty(model.FirstName) && x.FirstName == model.FirstName) || (!string.IsNullOrEmpty(model.LastName) && x.LastName == model.LastName) || (!string.IsNullOrEmpty(model.Patronymic) && x.Patronymic == model.Patronymic))?.GetViewModel; } public List GetFilteredList(EmployeeSearchModel model) { using var context = new PersonnelDepartmentDatabase(); return context.Employees .Where(x => (model.Id.HasValue && x.Id == model.Id) || (!string.IsNullOrEmpty(model.FirstName) && x.FirstName == model.FirstName) || (!string.IsNullOrEmpty(model.LastName) && x.LastName == model.LastName) || (!string.IsNullOrEmpty(model.Patronymic) && x.Patronymic == model.Patronymic)) .Select(x => x.GetViewModel).ToList(); } public List GetFullList() { using var context = new PersonnelDepartmentDatabase(); return context.Employees .Select(x => x.GetViewModel) .ToList(); } public EmployeeViewModel? Insert(EmployeeBindingModel model) { var newElement = Employee.Create(model); if (newElement == null) { return null; } using var context = new PersonnelDepartmentDatabase(); context.Employees.Add(newElement); context.SaveChanges(); return newElement.GetViewModel; } public EmployeeViewModel? Update(EmployeeBindingModel model) { using var context = new PersonnelDepartmentDatabase(); var element = context.Employees .FirstOrDefault(x => x.Id == model.Id); if (element == null) { return null; } element.Update(model); context.SaveChanges(); return element.GetViewModel; } } }