using SushiContracts.BindingModels; using SushiContracts.SearchModels; using SushiContracts.StorageContracts; using SushiContracts.ViewModels; using SushiDatabaseImplement.Models; using SushiDatabaseImplement; namespace SushiDatabaseImplement.Implements { public class ClientStorage : IClientStorage { public List GetFullList() { using var context = new SushiDatabase(); return context.Clients.Select(x => x.GetViewModel).ToList(); } public List GetFilteredList(ClientSearchModel model) { if (string.IsNullOrEmpty(model.ClientName)) { return new(); } using var context = new SushiDatabase(); return context.Clients.Where(x => x.ClientName.Contains(model.ClientName)).Select(x => x.GetViewModel).ToList(); } public ClientViewModel? GetElement(ClientSearchModel model) { if (string.IsNullOrEmpty(model.ClientName) && !model.Id.HasValue) { return null; } using var context = new SushiDatabase(); return context.Clients.FirstOrDefault(x => (!string.IsNullOrEmpty(model.ClientName) && x.ClientName == model.ClientName) || (model.Id.HasValue && x.Id == model.Id)) ?.GetViewModel; } public ClientViewModel? Insert(ClientBindingModel model) { var newClient = Client.Create(model); if (newClient == null) { return null; } using var context = new SushiDatabase(); context.Clients.Add(newClient); context.SaveChanges(); return newClient.GetViewModel; } public ClientViewModel? Update(ClientBindingModel model) { using var context = new SushiDatabase(); var client = context.Clients.FirstOrDefault(x => x.Id == model.Id); if (client == null) { return null; } client.Update(model); context.SaveChanges(); return client.GetViewModel; } public ClientViewModel? Delete(ClientBindingModel model) { using var context = new SushiDatabase(); var element = context.Clients.FirstOrDefault(rec => rec.Id == model.Id); if (element != null) { context.Clients.Remove(element); context.SaveChanges(); return element.GetViewModel; } return null; } } }