using Contracts.BindingModels; using Contracts.SearchModels; using Contracts.StoragesContracts; using Contracts.ViewModels; using DatabaseImplement.Models; namespace DatabaseImplement.Implements { public class ProductStorage : IProductStorage { public ProductViewModel? Delete(ProductBindingModel model) { using var context = new FactoryGoWorkDatabase(); var newProduct = context.Products.FirstOrDefault(x => x.Id == model.Id); if (newProduct == null) return null; context.Products.Remove(newProduct); context.SaveChanges(); return newProduct.GetViewModel; } public ProductViewModel? GetElement(ProductSearchModel model) { using var context = new FactoryGoWorkDatabase(); return context.Products.FirstOrDefault(x => (!string.IsNullOrEmpty(model.Name) && x.Name.Contains(model.Name)) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel; } public List GetFilteredList(ProductSearchModel 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.Products.Where(x => x.Id == model.Id).Select(x => x.GetViewModel).ToList(); } else if (model.UserId.HasValue) { return context.Products.Where(x => x.UserId == model.Id).Select(x => x.GetViewModel).ToList(); } else { return context.Products.Where(x => model.Name == x.Name).Select(x => x.GetViewModel).ToList(); } } public List GetFullList() { using var context = new FactoryGoWorkDatabase(); return context.Products.Select(x => x.GetViewModel).ToList(); } public ProductViewModel? Insert(ProductBindingModel model) { using var context = new FactoryGoWorkDatabase(); var newProduct = Product.Create(context, model); if (newProduct == null) return null; context.Products.Add(newProduct); context.SaveChanges(); return newProduct.GetViewModel; } public ProductViewModel? Update(ProductBindingModel model) { using var context = new FactoryGoWorkDatabase(); var newProduct = context.Products.FirstOrDefault(x => x.Id == model.Id); if (newProduct == null) return null; newProduct.Update(model); context.SaveChanges(); return newProduct.GetViewModel; } } }