using Contracts.BindingModels; using Contracts.SearchModels; using Contracts.StoragesContracts; using Contracts.ViewModels; using DatabaseImplement.Models; namespace DatabaseImplement.Implements { public class WorkerStorage : IWorkerStorage { public WorkerViewModel? Delete(WorkerBindingModel model) { using var context = new FactoryGoWorkDatabase(); var newWorker = context.Workers.FirstOrDefault(x => x.Id == model.Id); if (newWorker == null) return null; context.Workers.Remove(newWorker); context.SaveChanges(); return newWorker.GetViewModel; } public WorkerViewModel? GetElement(WorkerSearchModel model) { using var context = new FactoryGoWorkDatabase(); return context.Workers.FirstOrDefault(x => (!string.IsNullOrEmpty(model.Name) && x.Name.Contains(model.Name)) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel; } public List GetFilteredList(WorkerSearchModel model) { if (!model.Id.HasValue && string.IsNullOrEmpty(model.Name) && !model.UserId.HasValue) { return new(); } using var context = new FactoryGoWorkDatabase(); if (model.Id.HasValue) { return context.Workers.Where(x => x.Id == model.Id).Select(x => x.GetViewModel).ToList(); } else if (model.UserId.HasValue) { return context.Workers.Where(x => x.UserId == model.Id).Select(x => x.GetViewModel).ToList(); } else { return context.Workers.Where(x => model.Name == x.Name).Select(x => x.GetViewModel).ToList(); } } public List GetFullList() { using var context = new FactoryGoWorkDatabase(); return context.Workers.Select(x => x.GetViewModel).ToList(); } public WorkerViewModel? Insert(WorkerBindingModel model) { using var context = new FactoryGoWorkDatabase(); var newWorker = Worker.Create(model); if (newWorker == null) return null; context.Workers.Add(newWorker); context.SaveChanges(); return newWorker.GetViewModel; } public WorkerViewModel? Update(WorkerBindingModel model) { using var context = new FactoryGoWorkDatabase(); var newWorker = context.Workers.FirstOrDefault(x => x.Id == model.Id); if (newWorker == null) return null; newWorker.Update(model); context.SaveChanges(); return newWorker.GetViewModel; } } }