using Contracts.BindingModels; using Contracts.SearchModels; using Contracts.StoragesContracts; using Contracts.ViewModels; using DatabaseImplement.Models; using Microsoft.EntityFrameworkCore; namespace DatabaseImplement.Implements { public class MachineStorage : IMachineStorage { public MachineViewModel? Delete(MachineBindingModel model) { using var context = new FactoryGoWorkDatabase(); var newMachine = context.Machines.FirstOrDefault(x => x.Id == model.Id); if (newMachine == null) return null; newMachine.UpdateWorkers(context, model); context.Machines.Remove(newMachine); context.SaveChanges(); return newMachine.GetViewModel; } public MachineViewModel? GetElement(MachineSearchModel model) { using var context = new FactoryGoWorkDatabase(); return context.Machines.Include(p => p.Workers).ThenInclude(p => p.Worker).FirstOrDefault(x => (!string.IsNullOrEmpty(model.Title) && x.Title.Contains(model.Title)) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel; } public List GetFilteredList(MachineSearchModel model) { if (!model.UserId.HasValue) { return new(); } using var context = new FactoryGoWorkDatabase(); return context.Machines.Include(p => p.Workers).ThenInclude(p => p.Worker).Where(x => x.UserId == model.Id).Select(x => x.GetViewModel).ToList(); } public List GetFullList() { using var context = new FactoryGoWorkDatabase(); return context.Machines.Include(p => p.Workers).ThenInclude(p => p.Worker).Select(x => x.GetViewModel).ToList(); } public MachineViewModel? Insert(MachineBindingModel model) { using var context = new FactoryGoWorkDatabase(); var newMachine = Machine.Create(model, context); if (newMachine == null) return null; context.Machines.Add(newMachine); context.SaveChanges(); return newMachine.GetViewModel; } public MachineViewModel? Update(MachineBindingModel model) { using var context = new FactoryGoWorkDatabase(); var newMachine = context.Machines.FirstOrDefault(x => x.Id == model.Id); if (newMachine == null) return null; newMachine.Update(model); newMachine.UpdateWorkers(context, model); context.SaveChanges(); return newMachine.GetViewModel; } } }