using PlumbingRepairContracts.BindingModels; using PlumbingRepairContracts.SearchModels; using PlumbingRepairContracts.StoragesContracts; using PlumbingRepairContracts.ViewModels; using PlumbingRepairDatabaseImplement.Models; using Microsoft.EntityFrameworkCore; namespace PlumbingRepairDatabaseImplement.Implements { public class ImplementerStorage : IImplementerStorage { public ImplementerViewModel? Delete(ImplementerBindingModel model) { using var context = new PlumbingRepairDataBase(); var element = context.Implementers .Include(x => x.Orders) .FirstOrDefault(rec => rec.Id == model.Id); if (element != null) { context.Implementers.Remove(element); context.SaveChanges(); return element.GetViewModel; } return null; } public ImplementerViewModel? GetElement(ImplementerSearchModel model) { if (string.IsNullOrEmpty(model.ImplementerFIO) && string.IsNullOrEmpty(model.Password) && !model.Id.HasValue) { return null; } using var context = new PlumbingRepairDataBase(); return context.Implementers .FirstOrDefault(x => (string.IsNullOrEmpty(model.ImplementerFIO) || x.ImplementerFIO == model.ImplementerFIO) && (string.IsNullOrEmpty(model.Password) || x.Password == model.Password) && (!model.Id.HasValue || x.Id == model.Id)) ?.GetViewModel; } public List GetFilteredList(ImplementerSearchModel model) { if (model == null) { return new(); } if (!string.IsNullOrEmpty(model.ImplementerFIO)) { using var context = new PlumbingRepairDataBase(); return context.Implementers .Include(x => x.Orders) .Where(x => x.ImplementerFIO.Contains(model.ImplementerFIO)) .Select(x => x.GetViewModel) .ToList(); } return new(); } public List GetFullList() { using var context = new PlumbingRepairDataBase(); return context.Implementers .Include(x => x.Orders) .Select(x => x.GetViewModel) .ToList(); } public ImplementerViewModel? Insert(ImplementerBindingModel model) { var newImplementer = Implementer.Create(model); if (newImplementer == null) { return null; } using var context = new PlumbingRepairDataBase(); context.Implementers.Add(newImplementer); context.SaveChanges(); return newImplementer.GetViewModel; } public ImplementerViewModel? Update(ImplementerBindingModel model) { using var context = new PlumbingRepairDataBase(); var client = context.Implementers.FirstOrDefault(x => x.Id == model.Id); if (client == null) { return null; } client.Update(model); context.SaveChanges(); return client.GetViewModel; } } }