using ComputersShopContracts.BindingModels; using ComputersShopContracts.SearchModels; using ComputersShopContracts.StoragesContracts; using ComputersShopContracts.ViewModels; using ComputersShopDataBaseImplement.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ComputersShopDataBaseImplement.Implements { public class ClientStorage : IClientStorage { public ClientViewModel? Delete(ClientBindingModel model) { using var context = new ComputersShopDataBase(); var res = context.Clients.FirstOrDefault(x => x.Id == model.Id); if (res != null) { context.Clients.Remove(res); context.SaveChanges(); } return res?.GetViewModel; } public ClientViewModel? GetElement(ClientSearchModel model) { if (string.IsNullOrEmpty(model.ClientFIO) && string.IsNullOrEmpty(model.Email) && string.IsNullOrEmpty(model.Password) && !model.Id.HasValue) { return null; } using var context = new ComputersShopDataBase(); var temp = context.Clients .FirstOrDefault(x => (string.IsNullOrEmpty(model.ClientFIO) || x.ClientFIO == model.ClientFIO) && (string.IsNullOrEmpty(model.Email) || x.Email == model.Email) && (string.IsNullOrEmpty(model.Password) || x.Password == model.Password) && (!model.Id.HasValue || x.Id == model.Id)) ?.GetViewModel; return temp; } public List GetFilteredList(ClientSearchModel model) { if (model == null) { return new(); } if (model.Id.HasValue) { var res = GetElement(model); return res != null ? new() { res } : new(); } if (model.Email != null) { using var context = new ComputersShopDataBase(); return context.Clients .Where(x => x.Email.Contains(model.Email)) .Select(x => x.GetViewModel) .ToList(); } return new(); } public List GetFullList() { using var context = new ComputersShopDataBase(); return context.Clients.Select(x => x.GetViewModel).ToList(); } public ClientViewModel? Insert(ClientBindingModel model) { using var context = new ComputersShopDataBase(); var res = Client.Create(model); if (res != null) { context.Clients.Add(res); context.SaveChanges(); } return res?.GetViewModel; } public ClientViewModel? Update(ClientBindingModel model) { using var context = new ComputersShopDataBase(); var res = context.Clients.FirstOrDefault(x => x.Id == model.Id); res?.Update(model); context.SaveChanges(); return res?.GetViewModel; } } }