PIbd-22_Katysheva_N.E._Pizz.../Pizzeria/PizzeriaDatabaseImplement/Implements/OrderStorage.cs
2024-04-10 02:43:55 +04:00

81 lines
2.9 KiB
C#

using Microsoft.EntityFrameworkCore;
using PizzeriaContracts.BindingModels;
using PizzeriaContracts.SearchModels;
using PizzeriaContracts.StorageContracts;
using PizzeriaContracts.ViewModels;
using PizzeriaDatabaseImplement.Models;
namespace PizzeriaDatabaseImplement.Implements
{
public class OrderStorage : IOrderStorage
{
public OrderViewModel? GetElement(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
using var context = new PizzeriaDatabase();
return context.Orders.Include(x => x.Pizza).FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id))?.GetViewModel;
}
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
if (!model.Id.HasValue && !model.DateFrom.HasValue)
{
return new();
}
using var context = new PizzeriaDatabase();
if (model.DateFrom.HasValue)
{
return context.Orders.Include(x => x.Pizza).Where(x => x.DateCreate >= model.DateFrom && x.DateCreate <= model.DateTo).Select(x => x.GetViewModel).ToList();
}
return context.Orders.Include(x => x.Pizza).Where(x => x.Id == model.Id).Select(x => x.GetViewModel).ToList();
}
public List<OrderViewModel> GetFullList()
{
using var context = new PizzeriaDatabase();
return context.Orders.Include(x => x.Pizza).Select(x => x.GetViewModel).ToList();
}
public OrderViewModel? Insert(OrderBindingModel model)
{
var newOrder = Order.Create(model);
if (newOrder == null)
{
return null;
}
using var context = new PizzeriaDatabase();
context.Orders.Add(newOrder);
context.SaveChanges();
return context.Orders.Include(x => x.Pizza).FirstOrDefault(x => x.Id == newOrder.Id)?.GetViewModel;
}
public OrderViewModel? Update(OrderBindingModel model)
{
using var context = new PizzeriaDatabase();
var component = context.Orders.FirstOrDefault(x => x.Id == model.Id);
if (component == null)
{
return null;
}
component.Update(model);
context.SaveChanges();
return context.Orders.Include(x => x.Pizza).FirstOrDefault(x => x.Id == model.Id)?.GetViewModel;
}
public OrderViewModel? Delete(OrderBindingModel model)
{
using var context = new PizzeriaDatabase();
var element = context.Orders.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Orders.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}