using BeautySaloonContracts.BindingModels; using BeautySaloonContracts.SearchModels; using BeautySaloonContracts.StoragesContracts; using BeautySaloonContracts.ViewModels; using Microsoft.EntityFrameworkCore; namespace BeautySaloonDatabaseImplement.Implements { public class EmployeeStorage : IEmployeeStorage { public EmployeeViewModel? Delete(EmployeeBindingModel model) { using var context = new NewdbContext(); var element = context.Employees .Include(x => x.Position) .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) { using var context = new NewdbContext(); if (model.Id.HasValue) return context.Employees .Include(x => x.Position) .FirstOrDefault(x => x.Id == model.Id)? .GetViewModel; if (!string.IsNullOrEmpty(model.Phone)) return context.Employees .Include(x => x.Position) .FirstOrDefault(x => x.Phone.Equals(model.Phone))? .GetViewModel; return null; } public List GetFilteredList(EmployeeSearchModel model) { using var context = new NewdbContext(); if (string.IsNullOrEmpty(model.Surname) && !model.Id.HasValue) { return new(); } if (model.Id.HasValue) return context.Employees .Include(x => x.Position) .Where(x => x.Id.Equals(model.Id)) .Select(x => x.GetViewModel) .ToList(); return context.Employees .Include(x => x.Position) .Where(x => x.Surname.Contains(model.Surname)) .Select(x => x.GetViewModel) .ToList(); } public List GetFullList() { using var context = new NewdbContext(); return context.Employees .Include(x => x.Position) .Select(x => x.GetViewModel) .ToList(); } public EmployeeViewModel? Insert(EmployeeBindingModel model) { using var context = new NewdbContext(); model.Id = context.Employees.Count() > 0 ? context.Employees.Max(x => x.Id) + 1 : 1; var newEmployee = Employee.Create(model); if (newEmployee == null) { return null; } context.Employees.Add(newEmployee); context.SaveChanges(); return context.Employees .Include(x => x.Position) .FirstOrDefault(x => x.Id == newEmployee.Id)? .GetViewModel; } public EmployeeViewModel? Update(EmployeeBindingModel model) { using var context = new NewdbContext(); var client = context.Employees .Include(x => x.Position) .FirstOrDefault(x => x.Id == model.Id); if (client == null) { return null; } client.Update(model); context.SaveChanges(); return context.Employees .Include(x => x.Position) .FirstOrDefault(x => x.Id == client.Id)? .GetViewModel; } } }