Coursach/Course/DatabaseImplement/Implements/ProductStorage.cs
Sergey Kozyrev 95ed066239 ReportFirst
Work it harder, make it
Do it faster, makes us
More than ever, hour after hour
Work is never over
2024-04-30 21:51:49 +04:00

73 lines
2.5 KiB
C#

using Contracts.BindingModels;
using Contracts.SearchModels;
using Contracts.StoragesContracts;
using Contracts.ViewModels;
using DatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;
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;
newProduct.UpdateDetails(context, model);
context.Products.Remove(newProduct);
context.SaveChanges();
return newProduct.GetViewModel;
}
public ProductViewModel? GetElement(ProductSearchModel model)
{
using var context = new FactoryGoWorkDatabase();
return context.Products.Include(p => p.Details).ThenInclude(p => p.Detail).FirstOrDefault(x => (!string.IsNullOrEmpty(model.Name) && x.Name.Contains(model.Name)) || (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
}
public List<ProductViewModel> GetFilteredList(ProductSearchModel model)
{
if (!model.UserId.HasValue && !model.DetailId.HasValue)
{
return new();
}
using var context = new FactoryGoWorkDatabase();
if (model.DetailId.HasValue)
return context.Products.Include(p => p.Details).ThenInclude(p => p.Detail).Where(x => x.UserId == model.Id).Where(x => x.Details.FirstOrDefault(y => y.DetailId == model.DetailId) != null).Select(x => x.GetViewModel).ToList();
else
return context.Products.Include(p => p.Details).ThenInclude(p => p.Detail).Where(x => x.UserId == model.Id).Select(x => x.GetViewModel).ToList();
}
public List<ProductViewModel> GetFullList()
{
using var context = new FactoryGoWorkDatabase();
return context.Products.Include(p => p.Details).ThenInclude(p => p.Detail).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);
newProduct.UpdateDetails(context, model);
context.SaveChanges();
return newProduct.GetViewModel;
}
}
}